<?php
    /**
     * @file Post.php
     * @synopsis  用户发帖
     * @author Yee, <rlk002@gmail.com>
     * @version 1.0
     * @date 2015-03-11 17:31
     */
    
    
    class Postm extends CI_Model
    {
        const MC_KEY_POST4SEARCH = 'get_one_post_search_key_';
        const MC_KEY_TOP_POST_KEY = 'mc_key_top_post_';
        const MC_KEY_PIST_IMG_KEY = 'original_attachments_key1_';
        const MC_KEY_ALLPOSTLIST = 'get_all_post_key_';

        const POST_IMG_ANSWER       = 'http://proimg.medical-lighter.com/protect/ic_dynamic_answer.png@!origin';
        const POST_IMG_VOTE       = 'http://proimg.medical-lighter.com/protect/ic_dynamic_vote.png@!origin';

        function __construct()
        {
            parent::__construct();
            $this->load->model('favoritem');
            $this->load->model('commentm');
            $this->load->model('userm');
            $this->load->model('invitem');
            $this->load->model('rssm');
        }

        /**
         * 获取帖子详情
         * @param $post_id
         */
        public function get_post_info($post_id)
        {
            $result =  $this->db->select('*')
                ->from('ml_post')
                ->where('id', $post_id)
                ->get()
                ->row_array();
            return $result;
        }
        
        /*
         * 获取客户端 收藏数
         */
        public function get_post_list_for_user_favorite($where)
        {
            $sql = 'where = '.$where;
            $query = $this->db->query("select a.* ,b.username from ml_post as a left join ml_fellow as b on a.author_id=b.id where a.is_show=1 $where");
            return $query->result_array();
        }
        
        //获取帖子列表
        public function get_post_list_for_client($start,$page_size,$where)
        {
            $query = $this->db->query("select a.*,b.username as author_name from ml_post as a left join ml_fellow as b on a.author_id=b.id where a.is_show=1 $where order by a.addtime desc limit $start,$page_size");
            $query_result = $query->result_array();
            if($query_result)
            {
                $result = array();
                foreach($query_result as $row)
                {
                    $post_imgs = array();
                    $sharepic_imgs = array();
                    $post_imgs_original = $this->db->select("original,small")->where(array("pid"=>$row['id'],"cid"=>0))->order_by("sort","asc")->get("ml_attachments")->result_array();
                    if($post_imgs_original)
                    {
                        foreach ($post_imgs_original as $key)
                        {
                            if(!$key)
                            {
                                continue;
                            }
                            $post_imgs[] = ret_fullpath_url($key['original']);
                            $sharepic_imgs[] = ret_fullpath_url($key['small']);
                        }
                    }
                    $row['post_imgss'] = $post_imgs;
                    $comment_count = $this->commentm->get_count_for_client($row['id']);
                    $data_content = array();
                    $data_content['sharepic'] = $sharepic_imgs ? $sharepic_imgs[0] : '';
                    $data_content['id'] = $row['id'];
                    $data_content['author_id'] = $row['author_id'];
                    $data_content['author_name'] = $row['author_name'];
                    $data_content['post_imgs'] = $row['post_imgss'];
                    $data_content['aspect_ratio'] = $row['aspect_ratio'];
                    $data_content['comment_count'] = $comment_count;
                    $data_content['message'] = $row['message'];
                    $data_content['addtime'] = $row['addtime'];
                    $data_content['comment_addtime'] = $row['addtime'];
                    
                    $result[] = $data_content;
                }
                
            }
            else
            {
                $result = array();
            }
            return $result;
        }
        
        
        //获取帖子id 数组
        public function get_post_id_list($query, $start, $page_size, $params = array())
        {
            $this->db->select("id")->where($query);
            if ($params) {
                $this->db->where_in('post_type', $params);
            }
            $this->db->where_not_in('post_type_extend', array(4, 5))->order_by('addtime', 'desc');
            $query_result = $this->db->get("ml_post", $page_size, $start)->result_array();
            return $query_result;
        }

        /**
         * 获取我发的帖子IDS
         * @param $user_id
         * @param int $type
         */
        public function get_my_post_ids($user_id, $page, $page_size)
        {
            $key = MY_PUBLISH_LIST_PREFIX . $user_id . ':' . $page . ':' . $page_size;
            $result = unserialize($this->redis->get($key));
            if (empty($result)) {
                $start = ($page - 1) * $page_size;
                $filter = array('is_show' => 1, 'author_id' => $user_id);
                //$filter['post_type <>'] = 1;
                if (!in_array($user_id, [1, 14877, 31495])) { //轻盈帐号特殊处理
                   $filter['post_type <>'] = 1;
                }
                $result = $this->db->select('id')->where($filter)->where_not_in('post_type_extend', array(4,5,6))->order_by('addtime', 'DESC')->limit($page_size, $start)->get('ml_post')->result_array();
                if (!$result) return array();
                $this->redis->save($key, serialize($result), SPE_POST_INFO_STRING_KEY_EXPIRE_TIME);
            }
            return array_column($result, 'id');
        }
        
        /**
         * @param $page_size
         * @param $page
         * @param $is_rss
         * @param int $order 0- 正常 1-按热度 2-收藏 3- 评论
         * @return array
         */
        public function get_post_list($page_size, $page, $is_rss, $order = 0, $post_type_extend = 0, $hate_info = array())
        {
            if($is_rss) {
                //如果是医学生  实习医生 医学影像 护理 全科医生 都直接走全部列表
                $userinfo = $this->userm->getUserInfoById($this->uid);
                if($userinfo['thread'] == '-1' || $userinfo['thread'] == '-2' || $userinfo['thread'] == '135' || $userinfo['thread'] == '136' || $userinfo['thread'] == '126') {
                    $post_normal_id_list = $this->get_all_post_id_list($this->uid,$page,$page_size,$order,$post_type_extend, $hate_info);
                } else {
                    if (version_compare($this->softversion, "2.2.0") >= 0) {
                        $post_normal_id_list = $this->get_rss_post_id_list_2_2($this->uid, $page, $page_size, $order, $post_type_extend, $hate_info);
                    } else {
                        $post_normal_id_list = $this->get_rss_post_id_list($this->uid, $page, $page_size, $order);
                    }
                }
            } else {
                $post_normal_id_list = $this->get_all_post_id_list($this->uid,$page,$page_size,$order,$post_type_extend, $hate_info);
                w_debuglog('get_post_listm31:' . microtime(true)  .  '|uid:' . $this->uid . '|version:' . $this->softversion);
            }

            // 第一页添加置顶帖,推荐贴
            $top_post_id = $recommend_post_id = 0;
            if ($page == 1) {
                $this->load->model('digestm');
                $recommend_post_id = $this->digestm->get_recommend_post_id($this->uid, $post_type_extend);
                if ($recommend_post_id) {
                    $index = array_search($recommend_post_id, $post_normal_id_list);
                    if ($index !== false) unset($post_normal_id_list[$index]);
                    array_unshift($post_normal_id_list, $recommend_post_id);
                }

                if (version_compare($this->softversion, "2.2.0") >= 0) {
                    $top_post_id = $this->digestm->get_top_post_id($post_type_extend);
                } else {
                    $top_post_id = $this->get_top_post_id($this->pid);
                }

                if ($top_post_id) {
                    $index = array_search($top_post_id, $post_normal_id_list);
                    if ($index !== false) unset($post_normal_id_list[$index]);
                    array_unshift($post_normal_id_list, $top_post_id);
                }
            }

            if (!$post_normal_id_list) return array();
            w_debuglog('get_post_listm5:' . microtime(true)  .  '|uid:' . $this->uid . '|version:' . $this->softversion);


            $post_list = array();
            foreach($post_normal_id_list as $post_id) {
                $post_info = $this->get_one_post_4_search($post_id, $this->uid);
                if (!$post_info || !$this->is_in_post_list($post_info)) continue;
                $post_list[] = $post_info;
            }
            w_debuglog('get_post_listm6:' . microtime(true)  .  '|uid:' . $this->uid . '|version:' . $this->softversion);

            return array_values($post_list);

        }


        /**
         * V2.2 获取帖子列表
         * @param int $user_id
         * @param int $post_type_extend
         * @param $page
         * @param $page_size
         * @return array
         */
        public function get_post_list_for_2_2($user_id = 0, $post_type_extend = 0, $page, $page_size)
        {
            $hate_info = $userinfo = array();
            if ($user_id) {
                $this->load->model('hatem');
                $hate_info = $this->hatem->get_hatelist($user_id);
                $userinfo  = $this->userm->getUserInfoById($user_id);
            }

            //如果没有登录 或者 用户是医学生  实习医生 医学影像 护理 全科医生 都直接走全部列表
            if (!$userinfo || in_array($userinfo['thread'], array('-1','-2','135','136','126'))) {
                $post_ids = $this->get_all_post_id_list($user_id,$page,$page_size,0,$post_type_extend, $hate_info);
            } else {
                $post_ids = $this->rssm->get_user_rss_array_for_2_2($user_id, $post_type_extend, $page, $page_size, 0, $hate_info);
            }

            // 清除小红点提示
            $max_post_id = max($post_ids);
            if ($max_post_id && $page == 1 && in_array($post_type_extend, array(1,2,3))) {
                $this->load->model('unreadm');
                $this->unreadm->update_user_read_max_post_id($user_id, $max_post_id, $post_type_extend);
            }

            // 第一页添加置顶,推荐贴
            $top_post_id = $recommend_post_id = 0;
            if ($page == 1) {
                $this->load->model('digestm');
                $recommend_post_id = $this->digestm->get_recommend_post_id($user_id, $post_type_extend);
                if ($recommend_post_id) {
                    $index = array_search($recommend_post_id, $post_ids);
                    if ($index !== false) unset($post_ids[$index]);
                    array_unshift($post_ids, $recommend_post_id);
                }

                $top_post_id = $this->digestm->get_top_post_id($post_type_extend);
                if ($top_post_id) {
                    $index = array_search($top_post_id, $post_ids);
                    if ($index !== false) unset($post_ids[$index]);
                    array_unshift($post_ids, $top_post_id);
                }
            }

            // 收藏列表
            $fav_list_ids = $this->favoritem->get_fav_status($user_id,$post_ids);

            $post_list = array();
            foreach($post_ids as $post_id) {
                $post_info = $this->get_one_post_info($post_id);
                if (!$post_info || !$this->is_in_post_list($post_info)) continue;
                $post_info['favorite_status'] = in_array($post_id, $fav_list_ids) ? 1 : 0;
                $post_list[] = $post_info;
            }

            return array_values($post_list);
        }




        //获取所有的帖子

        function combine_recomment_post($uid, $post_type_extend=0)
        {
            $thread_recommand_post = $this->get_post_id_user_thread($uid,$post_type_extend);
            if($thread_recommand_post) {
                /*//更新帖子发帖时间*/
                if(isset($post_type_extend) && $post_type_extend){
                    $data_content = $this->get_one_post_4_search($thread_recommand_post['id'], $this->uid);
                }else{
                    $data_content = $this->get_one_post_4_search($thread_recommand_post['post_id'], $this->uid);
                }
                $data_content['message'] = $data_content['message'];
                $data_content['addtime'] = $thread_recommand_post['end_time'];  //  不能更新帖子的发帖时间 不然所有人都会看到推荐的帖子  只能照顾懂啊第一页 不能照顾到其他页面
                $data_content['addtime_cmdate'] = cgmdate($thread_recommand_post['end_time'], 'Y-m-d H:i:s');
                $data_content['start_time'] = $thread_recommand_post['start_time'];
                $data_content['end_time'] = $thread_recommand_post['end_time'];
                return $data_content;
            }
        }
        
        public function get_post_id_user_thread($user_id,$post_type_extend=0)
        {
            $threads = $this->rssm->get_user_rss_array($user_id);

            $recommends = array();
            foreach($threads as $thread)
            {
                if(isset($post_type_extend) && $post_type_extend){
                    $recommend_post_info = $this->recommend_post_for_thread_bytype($thread,$post_type_extend);
                }else{
                    $recommend_post_info = $this->recommend_post_for_thread($thread);
                }
                if($recommend_post_info)
                {
                    $recommends[] = $recommend_post_info;
                }
            }
            $recommend_count = count($recommends);
            $index = rand(0,$recommend_count > 0? $recommend_count -1 : 0);
            $one_recommend = $recommends[$index];
            return $one_recommend;
        }
        
        public function recommend_post_for_thread_bytype($thread,$post_type_extend)
        {
            $mc = $this->cache->memcached;
            $key = 'postm_get_post_id_user_thread_bytype' . $thread;
            if(!$this->cache->memcached->is_supported())
            {
                $result = array("code" => -3,'tips' => "缓存未开启");
            }
            $return = $mc->get($key);
            if(!$return){
                if(version_compare($this->softversion,'2.2.0')>=0)
                {
                    $return = $this->db->select('post_id as id,addtime,start_time,end_time,thread as type_id')->from('ml_digest_log')
                                       ->where('thread',$thread)
                                       ->where('post_type_extend',$post_type_extend)
                                       ->order_by('id','desc')
                                       ->limit(1,0)
                                       ->get()->result_array();
                 }else{
                    $return = $this->db
                        ->select("a.id ,a.addtime,b.type_id")
                        ->from('ml_post as a')
                        ->where('a.digest',1)
                        ->where('b.type_id',$thread)
                        ->where('a.post_type_extend',$post_type_extend)
                        ->join('ml_posttype as b','a.id=b.post_id','left')
                        ->order_by('a.addtime','desc')
                        ->limit(1,0)
                        ->get()
                        ->result_array();

                }
                $mc->save($key,$return,30*60);
            }
            $time = $this->db
                ->select('start_time,end_time')
                ->from('ml_digest_log')
                ->where('post_id',$return[0]['id'])
                ->where('thread',$return[0]['type_id'])
                ->where('post_type_extend', $post_type_extend)
                ->get()
                ->result_array();
            # 推荐时间
            $now_time = time();
            //查看生存时间
            if($return && ($time[0]['start_time'] <= $now_time && $time[0]['end_time'] > $now_time))
            {
                //生存时间
                $return[0]['exist_time'] = $time[0]['end_time'] - $time[0]['start_time'];
                return $return[0];
            }
            else
            {
                return array();
            }
        }
        
        public function recommend_post_for_thread($thread)
        {
            $mc = $this->cache->memcached;
            $key = 'postm_get_post_id_user_thread_' . $thread;
            if(!$this->cache->memcached->is_supported())
            {
                $result = array("code" => -3,'tips' => "缓存未开启");
            }
            $return = $mc->get($key);
            if(!$return)
            {
                $return = $this->db->select("post_id,addtime,thread,start_time,end_time")->where("thread",$thread)->where("is_show",1)->order_by("addtime","desc")->get("ml_digest_log",1,0)->result_array();
                $mc->save($key,$return,30*60);
            }

            $now_time = time();
            //如果有  并且在生效时间内
            //debug(($return && ($return[0]['start_time'] <= $now_time && $return[0]['end_time'] > $now_time)));
            if($return && ($return[0]['start_time'] <= $now_time && $return[0]['end_time'] > $now_time))
            {
                //生存时间
                $return[0]['exist_time'] = $return[0]['end_time'] - $return[0]['start_time'];
                return $return[0];
            }
            else
            {
                return array();
            }
        }

        public function get_one_post_4_search($post_id,$observer_id,$cache=1)
        {
            if (version_compare($this->softversion, "2.1.0")>=0) {
                return self::get_one_post_4_search_for_2_1($post_id,$observer_id,$cache);
            }

            $row = $this->one_post_content($post_id,$cache);
            if(!$row)
            {
                return array();
            }

            $tmp_no_cache_img = 0;
            if (time() - $row["addtime"] < 180) {
                // 防止图片入库过程中被错误缓存
                $tmp_no_cache_img = 1;
            }

            $mc = $this->cache->memcached;
            $post_imgs = array();
            $sharepic_imgs = array();

            $img_mc_key = self::MC_KEY_PIST_IMG_KEY.$post_id;
            $post_imgs_original = $mc->get($img_mc_key);
            if(!$post_imgs_original || $cache != 1 || $tmp_no_cache_img)
            {
                $post_imgs_original = $this->db->select("original,small,width,height")->where(array("pid"=>$post_id,"cid"=>0))->order_by("sort","asc")->get("ml_attachments")->result_array();

                $time_out = 24*60*60;
                $mc->save($img_mc_key,$post_imgs_original, $time_out);
            }

            $images_ratio = array();
            foreach ($post_imgs_original as $one_image)
            {
                $img_path = ret_fullpath_url($one_image['original']);
                $post_imgs[] = $img_path;
                $sharepic_imgs[] = ret_fullpath_url($one_image['small']);

                $img_width = $one_image['width'];
                $img_height = $one_image['height'];
                //高比宽
                # 修改bug
                if($img_width){
                    $ratio = $img_height/$img_width;
                }
                if(!$ratio)
                {
                    $ratio  = 1.16;
                }
                $images_ratio[] = $ratio;
            }
            $favorite_count = $this->favoritem->get_post_fav_count($post_id);

            //如果用户为-1  说明是没有注册 则全部显示没有收藏
            //$this->params['author_id'] = "3032";
            $this->uid = $this->uid ? $this->uid : $this->input->get("user_id");
            if(isset($this->uid) && $this->uid > 0)
            {
                $favorite_count_status = $this->favoritem->is_fav($this->uid, $row['id']);
            }
            else
            {
                $favorite_count_status = 0;
            }
            $favorite_status = $favorite_count_status ? "1" : "0";
            $data_content = array();
            $data_content['id'] = $post_id;
            $data_content['author_id'] = $row['author_id'];
            $data_content['verified_status'] = $row['verified_status'];

            $first_ratio = $images_ratio[0];
            if(!$first_ratio)
            {
                $first_ratio  = 1.16;
            }
            $data_content['first_img_ratio'] = $first_ratio;
            $data_content['imgs_ratio'] = $images_ratio;
            $data_content['limit_ratio'] = 1.16;

            if (!isset($this->threadm)) {
                $this->load->model('threadm');
            }
            $data_content["thread_name"] = $this->threadm->get_thread_name($row["thread"]);

            $data_content['admin_level'] = $row['admin_level'];
            $data_content['is_expert'] = $row['user_level'] ? 1 : 0;
            $data_content['digest'] = $row['digest'];
            $data_content['author_name'] = $row['author_name'];
            $data_content['head_ico'] = ret_fullpath_url($row['head_ico']);

            // 观察者与被观察者为同一人时 返回 0
            if($row['author_id'] == $this->uid)
            {
                $follow_status = 0;
            }
            else
            {
                //否则检查是否关注过
                $this->load->model('followm');
                $friend_list = $this->followm->get_mutual_ids($row['author_id']);
                $follow_status = $this->followm->get_follow_status($this->uid, $row['author_id']);
            }
            $data_content['follow_status'] = $follow_status;


            //$data_content['author_name'] = $row['admin_level'] > 2 ? "🔅".$row['author_name'] : $row['author_name'];
            $data_content['post_imgs'] = $post_imgs;
            $data_content['is_recommend'] = "0"; //是否为推荐帖子 推荐帖子 关闭时间显示
//            $data_content['aspect_ratio'] = $row['aspect_ratio']; 改从数组里取

            $aspect_ratio = $images_ratio ? max($images_ratio) : 0;
            $data_content['aspect_ratio'] = $aspect_ratio;

            $data_content['comment_count'] = (string)$this->commentm->get_count_for_client($row['id']);


            $data_content['share_desc'] = mb_substr($row['message'],0,30,'utf-8');
            $data_content['share_url'] = WEB_URL.'share/threads/'.$post_id;
            if(isset($row['post_type_extend']) && ($row['post_type_extend'] == 4 || $row['post_type_extend'] == 5))
            {
                $data_content['share_url'] = WEB_URL.'share/post_share_detail/'.$post_id;
            }

            //这里不能根据帖子类型post_type_extend 来判断message的内容 而是应该用post_type  来判断是否拼接
            if($row['post_type'] == 1 || $row['post_type'] == 11 )
            {
                if($row['post_type_extend'] == 1 || $row['post_type_extend'] == 2){
                    $specialist_post_info = $this->get_specialist_post_info_extend($post_id);
                }else{
                    $specialist_post_info = $this->get_specialist_post_info($post_id);
                }
                $row['message'] = $specialist_post_info['return'];
                $data_content['share_desc'] = mb_substr($specialist_post_info['result']['tell_history'],0,30,'utf-8');

                $rt = $this->invitem->invite_list_db($post_id);
                $invitelist = $rt['invites'];
                $invited_ids = array_keys($invitelist);
                $data_content['all_invited'] = $invited_ids;
                $data_content['is_showall'] = $specialist_post_info['result']['is_showall'];
            }

            $old_to_new_data = $this->oldcontent_pregmatch_index($row['message']);
            $message = $old_to_new_data['message'];
            $adds = $old_to_new_data['adds'];
            //帖子内容展示 兼容旧版本
            if(($this->pid == "2002" && version_compare($this->softversion, "1.7.0")>0) || ($this->pid == "3001" && version_compare($this->softversion, "1.7.0")>0))
            {
                //老帖子碰上新版，将老帖子分割成新帖格式
                if($adds)//老帖新版本
                {
                    $data_content['message'] = $message;
                    $note = '补充：';
                    for($add_index = 0; $add_index < 4; $add_index++ )
                    {
                        if($adds[$add_index])
                        {
                            $conent_key = 'add_content'.($add_index + 1);
                            $img_key = 'add_img_index_'.($add_index + 1);

                            $data_content[$conent_key] = $note.$adds[$add_index]['add_centent'];
                            $adds[$add_index]['index2'] = $adds[$add_index]['index2'] ? $adds[$add_index]['index2'] : $adds[$add_index]['index1'];
                            $data_content[$img_key] = $adds[$add_index]['index1'].'-'.$adds[$add_index]['index2'];
                            if($adds[$add_index]['index2'] > 0)
                            {
                                $count = (int)$adds[$add_index]['index2'] - (int)$adds[$add_index]['index1'] + 1;
                            }
                            else
                            {
                                $count = 1;
                            }
                            $data_content[$conent_key] = $data_content[$conent_key].'(新增'.(string)$count.'张图片)';
                        }
                    }
                    //老帖新补充
                    if($row['add_content1'])
                    {
                        $this->compatible_post_join($data_content,$row,count($adds));
                    }
                }
                else//新帖新版本
                {
                    $data_content['message'] = $row['attachment'] ? $row['message']."\r\n".$row['attachment'] : $row['message'];
                    $this->new_post_join($data_content,$row);
                }
            }
            else
            {
                //新帖碰上老版本
                if($adds)//老帖老版本
                {
                    $data_content['message'] = $row['attachment'] ? $row['message']."\r\n".$row['attachment'] : $row['message'];
                }
                else//新帖老版本
                {
                    $data_content['message'] = $row['message'];
                    for ($add_index = 1; $add_index <= 4; $add_index++)
                    {
                        $conent_key = 'add_content' . $add_index;
                        $img_key = 'add_img_index_' . $add_index;

                        $indexs = explode('-', $row[$img_key]);

                        if(count($indexs) > 1) {
                            if ($indexs[0] == $indexs[1]) {

                                $add_content = '补充：' . $row[$conent_key] . '(新增第' . $indexs[0] . '张图片)';
                            } else {
                                $add_content = '补充：' . $row[$conent_key] . '(新增第' . $indexs[0] . ' - ' . $indexs[1] . '张图片)';
                            }

                            $data_content['message'] = $row[$conent_key] ? $data_content['message'] . "\r\n" . $add_content : $data_content['message'];
                        }

                    }
                    $data_content['message'] = $row['attachment'] ? $data_content['message'] . "\r\n" . $row['attachment'] : $data_content['message'];
                }
            }

            $data_content['post_type'] = $row['post_type'];
            $data_content['post_type_extend'] = $row['post_type_extend'];
            $data_content['subject'] = $row['subject'];
            $data_content['typeid'] = $row['typeid'];
            $data_content['attachment'] = $row['attachment'];
            $data_content['at_friend_list'] = $row['at_friend_list_id_array'] ? $this->get_friend_list($row['at_friend_list_id_array']) : ""; //如果没有  就是 空
            $data_content['addtime'] = $row['addtime'];
            $data_content['create_time'] = $row['create_time'];
            $data_content['addtime_cmdate'] = cgmdate($row['addtime'],'Y-m-d H:i:s');
//            $data_content['comment_addtime'] = $val['addtime'];
            $data_content['sharepic'] = $sharepic_imgs[0];
            $data_content['favorite_count'] = (string)$favorite_count;
            $data_content['favorite_status'] = $favorite_status;
            //$this->cache->save('searchdata_' . $post_id,$data_content,7200);
            //iPhone 1.8.1开始，补充内容放数组返回
            if($this->pid == "2002" && version_compare($this->softversion, "1.8.0")>0 ||$this->pid == "3001" && version_compare($this->softversion, "1.6.0")>0)
            {
                $add_contents = array();
                $add_img_indexs = array();
                for ($add_index = 1; $add_index <= 4; $add_index++)
                {
                    $content_key = 'add_content'.$add_index;
                    $img_key = 'add_img_index_'.$add_index;
                    if($data_content[$content_key] )
                    {
                        $add_contents[] = $data_content[$content_key];
                        $add_img_indexs[] = $data_content[$img_key];
                    }
                }
                if($add_contents)
                {
                    $data_content['add_contents'] = $add_contents;
                    $data_content['add_img_indexs'] = $add_img_indexs;
                }
            }
            $post_id = $row['id'];
            if($row['answer_index']&&$row['answer_index'] >0)
            {
                $data_content['have_answer'] = 1;
            }
            else
            {
                $answer = $this->commentm->get_post_answer($post_id);
                if($answer)
                {
                    $data_content['have_answer'] = 1;
                }
            }

            $data_content['is_top'] = $row['is_top'];

            //实名
            if($row['is_show_truename'] == 1)
            {
                if($row['truename'] && strcmp($row['truename'], $row['author_name']) != 0)
                {
                    $data_content['author_name'] = $row['truename'].'「'.$row['author_name'].'」';
                }
            }

            //认证用户展示医院
            if($row['verified_status'] == 3)
            {
                //取认证医院
                $verified_info = $this->userm->verified_info($row['author_id']);
                $hospital =  $verified_info['hospital'];
                if(!$hospital)
                {
                    $hospital = $row['practice_hospital'];
                }
                $data_content['practice_hospital'] = $hospital;
                if(version_compare($this->softversion, '1.9.3') <= 0) {
                    $data_content['thread_name'] = $hospital . ' ' . $data_content['thread_name'];
                }
                else
                {
                    if(is_numeric($row['post_title']))
                    {
                        ci_load_once('posttitlem');
                        $row['post_title'] = $this->posttitlem->getPosttitleName($row['post_title']);
                    }
                    $data_content['thread_name'] = $data_content['thread_name'].' '.$row['post_title'];
                }
            }

            $data_content["paid_success"] = $row["paid_success"];
            $data_content["is_pinpai"] = $row["is_pinpai"];
            # 获取投票帖选项
            if(isset($row['post_type_extend']) && $row['post_type_extend'] == 5)
            {
                $data_content['option'] = $this->get_vote_list($post_id);
                $data_content['total_count'] = $this->get_total_count($post_id);
                $data_content['click_num'] = $this->get_click_vote($post_id,$this->uid);
            }
            return $data_content;
        }

        /**
         * 获取单条帖子信息 拼接动态信息
         * @param int $post_id
         * @param int $cache
         */
        public function get_one_post_info($post_id = 0, $cache = 1, $is_fav = 0)
        {
            // 静态数据
            $data = Postm::get_post_content($post_id, $cache);
            if (!$data) return array();

            // 拼接图片信息
            $this->load->model('attachmentsm');
            $img_info = $this->attachmentsm->get_post_img_info($post_id);
            $data['first_img_ratio'] = isset($img_info['img_ratio'][0]) ? $img_info['img_ratio'][0] : 1.16;
            if (version_compare($this->softversion, "2.3") >= 0) {
                if ($data['first_img_ratio'] >= 0.72) {
                    $data['first_img_ratio'] = 0.72;
                }
            }
            $data['imgs_ratio']      = $img_info['img_ratio'];
            $data['limit_ratio']     = 1.16;
            $data['aspect_ratio']    = !empty($img_info['img_ratio']) ?  max($img_info['img_ratio']) : 1.16;
            if (version_compare($this->softversion, "2.3") >= 0) {
                $data['limit_ratio'] = 0.67;
                $data['aspect_ratio'] = !empty($img_info['img_ratio']) ? max($img_info['img_ratio']) : 1.16;
                if ($data['aspect_ratio'] >= 1.5) {
                    $data['aspect_ratio'] = 1.5;
                }
            }
            $data['post_imgs']       = $img_info['img_list'];
            $data['sharepic']        = isset($img_info['share_img_list'][0]) ? $img_info['share_img_list'][0] : '';

            // 拼接动态数据
            $data['favorite_count']  = $this->favoritem->get_post_fav_count($post_id, $cache);
            $data['comment_count']   = $this->commentm->get_count_for_client($post_id, $cache);
            $data['follow_status']   = $this->followm->get_follow_status($this->uid, $data['author_id']);
            $data['addtime_cmdate']  = cgmdate($data['create_time'],'Y-m-d H:i:s');

            // 无语,先这样吧 为了优化列表的sql
            if ($is_fav) {
                $data['favorite_status'] = $this->favoritem->is_fav($this->uid, $post_id);
            }

            if($data['post_type_extend'] == 5) {
                $data['option']      = $this->get_vote_list($post_id, $cache);
                $data['total_count'] = $this->get_total_count($post_id, $cache);
                $data['click_num']   = $this->get_click_vote($post_id, $this->uid);
                // 2.2.2  投票问答新增文案修改
                $data['share_desc'] = $data['total_count'] . '个人参与了文字投票,' . $data['comment_count'] . '个人评论了文字投票';
            }

            // 2.4 需求新增帖子打赏金额
            $balance = $this->getBonusMoney($post_id);
            ci_load_once('tradem');
            $data['money'] = round($this->tradem->convertFen2Yuan($balance), 2);

            return $data;
        }


        /**
         * 获取单条帖子 静态信息 拼接后存入redis
         * @param $post_id
         */
        public function get_post_content($post_id, $cache = 1)
        {
            $key = POST_INFO_STRING_PREFIX.$post_id;
            $data = unserialize($this->redis->get($key));
            if (!$data || $cache == 0) {
                $filter = array('a.id' => $post_id, 'a.is_show' => 1);
                $result = $this->db->select('a.*, b.practice_hospital, b.thread, b.username as author_name, b.head_ico, b.verified_status, b.admin_level, b.user_level, b.is_show_truename, b.truename, b.practice_hospital, b.post_title,')
                    ->from('ml_post   as a')
                    ->join('ml_fellow as b', 'a.author_id=b.id', 'left')
                    ->where($filter)
                    ->get()
                    ->row_array();

                if ($result) {
                    $this->load->model('threadm');
                    $create_time = !empty($result['create_time']) ? $result['create_time'] : $result['addtime'];

                    // 2.3 part2
                    if (!empty($result['sex']) && $result['age'] !== '') {
                        if ($result['sex'] == 1) {
                            $message = "患者性别：男，年龄：" . $result['age'] . "。\r\n" . $result['message'];
                        } elseif ($result['sex'] == 2) {
                            $message = "患者性别：女，年龄：" . $result['age'] . "。\r\n" . $result['message'];
                        } else {
                            $message = $result['message'];
                        }
                    } else {
                        $message = $result['message'];
                    }

                        $data = array(
                            'id'                => $post_id,
                            'author_id'         => $result['author_id'],
                            'verified_status'   => $result['verified_status'],
                            'thread_name'       => $this->threadm->get_thread_name($result['thread']),
                            'admin_level'       => $result['admin_level'],
                            'is_expert'         => $result['user_level'] ? 1 : 0,
                            'digest'            => $result['digest'],
                            'author_name'       => $result['author_name'],
                            'attachment'        => $result['attachment'],
                            'post_type_extend'  => $result['post_type_extend'],
                            'subject'           => $result['subject'],
                            'is_pinpai'         => $result['is_pinpai'],
                            'head_ico'          => ret_fullpath_url($result['head_ico']),
                            'share_title'       => $result['author_name'].' '.$result['practice_hospital'],
                            'share_desc'        => mb_substr($result['message'], 0, 30,'utf-8'),
                            'share_url'         => Postm::get_share_url($post_id, $result['post_type_extend']),
                            'post_type'         => $result['post_type'],
                            'typeid'            => $result['typeid'],
                            'addtime'           => $create_time,
                            'create_time'       => $result['create_time'],
                            'is_recommend'      => $result['is_recommend'],
                            'is_top'            => $result['is_top'],
                            'paid_success'      => $result['paid_success'],
                            'message' => $message,
                            'practice_hospital' => $result['practice_hospital'],
                            'have_answer'       => 0,
                            'answer_index' => $result['answer_index'],
                            'sex' => $result['sex'],
                            'age' => $result['age']
                        );

                    // 实名用户
                    if ($result['is_show_truename'] && $result['truename'] != $result['author_name']){
                        $data['author_name'] =  $result['truename'].'「'.$result['author_name'].'」';
                    }

                    // 认证用户展示医院 科室 职称
                    if ($result['verified_status'] == 3) {
                        ci_load_once('posttitlem');
                        $post_title = $this->posttitlem->getPosttitleName($result['post_title']);

                        $data['thread_name'] = $data['thread_name'].' '.$post_title;
                    }

                    // 问答取message
                    if ($result['post_type_extend'] == 4) {
                        $share_desc = !empty($result['message']) ? $result['message'] : $result['subject'];
                        $data['share_desc'] = mb_substr($share_desc, 0, 30, 'utf-8');
                    }

                    //是否有答案
                    if($result['answer_index'] && $result['answer_index'] > 0) {
                        $data['have_answer'] = 1;
                    } else {
                        $answer = $this->commentm->get_post_answer($post_id);
                        if($answer) {
                            $data['have_answer'] = 1;
                        }
                    }

                    // 根据帖子类型不同, 拼接 message 字段。并针对特殊类型帖子进行处理。
                    Postm::get_messages($data, $result['post_type']);
                    Postm::get_add_contents($data, $result);

                    $res = $this->redis->save($key, serialize($data), POST_INFO_STRING_KEY_EXPIRE_TIME);
                }
            }
            return $data;
        }

        /**
         * 获取帖子的分享连接
         * @param $post_id
         * @param $post_type_extend
         * @return string
         */
        public function get_share_url($post_id, $post_type_extend)
        {
            $share_url = WEB_URL.'share/threads/'.$post_id;
            if (in_array($post_type_extend, array(4,5))) {
                $share_url = WEB_URL.'share/post_share_detail/'.$post_id;
            }
            else if($post_type_extend == 6) //专家咨询帖
            {
                $share_url = WEB_URL.'share/specialist_post/'.$post_id;
            }
            return $share_url;
        }

        /**
         * 获取补充内容 内容+图片
         * @param $results
         * @return array
         */
        public function get_add_contents(&$data, $results)
        {
            $add_contents = $add_img_indexs = array();

            for ($i = 1; $i <= 6; $i++) {
                $conent_key = 'add_content' . $i;
                $img_key    = 'add_img_index_' . $i;
                $time_key = 'add_time_' . $i;
                #有答案
                if($results['answer_index']> 0 &&$results['answer_index'] == $i)
                {
                      $key = "答案: ";
                }else{
                      $key = "补充: ";
                }
                if ($results[$conent_key]) {
                    $indexs = explode('-', $results[$img_key]);
                    // 判断有没有图
                    if(count($indexs) > 1 && $indexs[0] > 0 && $indexs[1] > 0) {
                        if ($indexs[0] == $indexs[1]) { // 只有一张图
                            if ($results[$time_key]) {
                                $add_content = $key . $results[$conent_key] . ' (' . date('Y-m-d', $results[$time_key]) . '新增第' . $indexs[0] . '张图片)';
                            } else {
                                $add_content = $key . $results[$conent_key] . '(新增第' . $indexs[0] . '张图片)';
                            }
                        } else { // 多张图
                            if ($results[$time_key]) {
                                $add_content = $key . $results[$conent_key] . ' (' . date('Y-m-d', $results[$time_key]) . '新增第' . $indexs[0] . ' - ' . $indexs[1] . '张图片)';
                            } else {
                                $add_content = $key . $results[$conent_key] . '(新增第' . $indexs[0] . ' - ' . $indexs[1] . '张图片)';
                            }
                        }
                    } else { // 没图
                        if ($results[$time_key]) {
                            $add_content = $key . $results[$conent_key] . ' (' . date('Y-m-d', $results[$time_key]) . ')';
                        } else {
                            $add_content = $key . $results[$conent_key];
                        }
                    }

                    /*  if ($results['answer_index'] > 0 && $results['answer_index'] == $i) {
                          $answer_contents = $add_content;
                          $answer_img_indexs = $results[$img_key];

                      } else {
                          $add_contents[] = $add_content;
                          $add_img_indexs[] = $results[$img_key];
                      }
                      $data[$conent_key] = $add_content;
                      $data[$img_key]    = $results[$img_key];
                      $data[$time_key] = $results[$time_key];
                  }
              }
              if (isset($answer_contents) && $answer_contents) {
                  array_push($add_contents, $answer_contents);
                  array_push($add_img_indexs, $answer_img_indexs);
                  $data['add_contents'] = $add_contents;
                  $data['add_img_indexs'] = $add_img_indexs;
              } else {
                  $data['add_contents'] = $add_contents;
                  $data['add_img_indexs'] = $add_img_indexs;
              }*/

                    $add_contents[] = $add_content;
                    $add_img_indexs[] = $results[$img_key];
                    $data[$conent_key] = $add_content;
                    $data[$img_key] = $results[$img_key];
                    $data[$time_key] = $results[$time_key];
                }
            }

            $data['add_contents'] = $add_contents;
            $data['add_img_indexs'] = $add_img_indexs;
            return true;

        }

        /**
         * 拼接message数据
         * @param $data
         * @param int $post_type
         */
        public function get_messages(&$data, $post_type = 0)
        {
            if ($post_type == 1) { // 专家贴
                $specialist_post_info = $this->get_specialist_post_info($data['id']);
                $data['message'] = $specialist_post_info['return'];
                //$data['share_desc'] = mb_substr($specialist_post_info['result']['tell_history'],0,30,'utf-8');

                $rt = $this->invitem->invite_list_db($data['id']);
                $invitelist          = $rt['invites'];
                $invited_ids         = array_keys($invitelist);
                $data['all_invited'] = $invited_ids;
                $data['is_showall']  = $specialist_post_info['result']['is_showall'];
                $data['share_title'] = '轻盈医学病例咨询意见';
                $expert_info = $this->userm->getUserInfo($invited_ids[0]);w_log(json_encode($expert_info));
                $data['share_desc'] = '受邀专家:'.$expert_info['truename'].' '.$expert_info['practice_hospital'];

            } else if ($post_type == 11) { // 分享贴
                if ($data['post_type_extend'] == 1 && $data['message']) {
                    return false;
                } else {
                    $specialist_post_info = $this->get_specialist_post_info_extend($data['id']);
                    $data['message'] = $specialist_post_info['return'];
                    $data['share_desc'] = mb_substr($specialist_post_info['result']['tell_history'], 0, 30, 'utf-8');
                    $data['is_showall'] = $specialist_post_info['result']['is_showall'];
                }

            } else {
                return false;
            }
            return true;
        }

        /**
         * v2.1 shiwuhao
         * @param $post_id
         * @param $observer_id
         * @param int $cache
         * @return array
         */
        public function get_one_post_4_search_for_2_1($post_id,$observer_id = '',$cache=1)
        {
            $row = $this->one_post_content($post_id,$cache);
            if(!$row)
            {
                return array();
            }

            $tmp_no_cache_img = 0;
            if (time() - $row["addtime"] < 180) {
                // 防止图片入库过程中被错误缓存
                $tmp_no_cache_img = 1;
            }

            $mc = $this->cache->memcached;
            $post_imgs = array();
            $sharepic_imgs = array();

            $img_mc_key = self::MC_KEY_PIST_IMG_KEY.$post_id;
            $post_imgs_original = $mc->get($img_mc_key);
            if(!$post_imgs_original || $cache != 1 || $tmp_no_cache_img)
            {
                $post_imgs_original = $this->db->select("original,small,width,height")->where(array("pid"=>$post_id,"cid"=>0))->order_by("sort","asc")->get("ml_attachments")->result_array();

                $time_out = 24*60*60;
                $mc->save($img_mc_key,$post_imgs_original, $time_out);
            }

            $images_ratio = array();
            $this->load->model('followm');
            foreach ($post_imgs_original as $one_image)
            {
                $img_path = ret_fullpath_url($one_image['original']);
                $post_imgs[] = $img_path;
                $sharepic_imgs[] = ret_fullpath_url($one_image['small']);

                $img_width = $one_image['width'];
                $img_height = $one_image['height'];
                //高比宽
                if(isset($img_width) && $img_width){
                    $ratio = $img_height/$img_width;
                }
                if(!$ratio)
                {
                    $ratio  = 1.16;
                }
                $images_ratio[] = $ratio;
            }
            $favorite_count = $this->favoritem->get_post_fav_count($post_id);

            //如果用户为-1  说明是没有注册 则全部显示没有收藏
            //$this->params['author_id'] = "3032";
            $this->uid = $this->uid ? $this->uid : $this->input->get("user_id");
            if(isset($this->uid) && $this->uid > 0)
            {
                $favorite_count_status = $this->favoritem->is_fav($this->uid, $row['id']);
            }
            else
            {
                $favorite_count_status = 0;
            }
            $favorite_status = $favorite_count_status ? "1" : "0";
            $data_content = array();
            $data_content['id'] = $post_id;
            $data_content['author_id'] = $row['author_id'];
            $data_content['verified_status'] = $row['verified_status'];

            $first_ratio = (!$images_ratio[0]) ? 1.16 : $images_ratio[0];
            $data_content['first_img_ratio'] = $first_ratio;

            if (version_compare($this->softversion, "2.3") >= 0) {
                if ($data_content['first_img_ratio'] >= 0.72) {
                    $data_content['first_img_ratio'] = 0.72;
                }
            }

            $data_content['imgs_ratio'] = $images_ratio;
            $data_content['limit_ratio'] = 1.16;

            if (!isset($this->threadm)) {
                $this->load->model('threadm');
            }
            $data_content["thread_name"] = $this->threadm->get_thread_name($row["thread"]);

            $data_content['admin_level'] = $row['admin_level'];
            $data_content['is_expert'] = $row['user_level'] ? 1 : 0;
            $data_content['digest'] = $row['digest'];
            $data_content['author_name'] = $row['author_name'];
            $data_content['attachment'] = $row['attachment'];
            $data_content['post_type_extend'] = $row['post_type_extend'];
            $data_content['subject'] = $row['subject'];
            $data_content['is_pinpai'] = $row['is_pinpai'];
            $data_content['special_post'] = $row['special_post'];
            $data_content['head_ico'] = ret_fullpath_url($row['head_ico']);

            // 观察者与被观察者为同一人时 返回 0
            if($row['author_id'] == $this->uid)
            {
                $follow_status = 0;
            }
            else
            {
                $friend_list = $this->followm->get_mutual_ids($row['author_id']);
                $follow_status = $this->followm->get_follow_status($this->uid, $row['author_id']);
            }
            $data_content['follow_status'] = $follow_status;


            //$data_content['author_name'] = $row['admin_level'] > 2 ? "🔅".$row['author_name'] : $row['author_name'];
            $data_content['post_imgs'] = $post_imgs;
            $data_content['is_recommend'] = "0"; //是否为推荐帖子 推荐帖子 关闭时间显示
            //            $data_content['aspect_ratio'] = $row['aspect_ratio']; 改从数组里取
            if(isset($images_ratio) && $images_ratio){
                $aspect_ratio = max($images_ratio);
            }
            $data_content['aspect_ratio'] = $aspect_ratio;

            // 2.3 需求
            if (version_compare($this->softversion, "2.3") >= 0) {
                $data_content['limit_ratio'] = 0.67;
                if ($data_content['aspect_ratio'] >= 1.5) {
                    $data_content['aspect_ratio'] = 1.5;
                }
            }
            $data_content['comment_count'] = (string)$this->commentm->get_count_for_client($row['id']);


            $data_content['share_desc'] = mb_substr($row['message'],0,30,'utf-8');
            if($row['post_type'] == 1)
            {
                $data_content['share_url'] = WEB_URL.'share/specialist_post/'.$post_id;
            }
            else
            {
                $data_content['share_url'] = WEB_URL.'share/threads/'.$post_id;
            }
            if(isset($row['post_type_extend']) && ($row['post_type_extend'] == 4 || $row['post_type_extend'] == 5))
            {
                $data_content['share_url'] = WEB_URL.'share/post_share_detail/'.$post_id;
            }

//            if($row['post_type'] == 1 || $row['post_type_extend'] == 1 || $row['post_type_extend'] == 2)
//            {
//                if($row['post_type_extend'] == 1 || $row['post_type_extend'] == 2){
//                    $specialist_post_info = $this->get_specialist_post_info_extend($post_id);
//                }else{
//                    $specialist_post_info = $this->get_specialist_post_info($post_id);
//                }
//                $row['message'] = $specialist_post_info['return'];
//                $data_content['share_desc'] = mb_substr($specialist_post_info['result']['tell_history'],0,30,'utf-8');
//
//                $rt = $this->invitem->invite_list_db($post_id);
//                $invitelist = $rt['invites'];
//                $invited_ids = array_keys($invitelist);
//                $data_content['all_invited'] = $invited_ids;
//                $data_content['is_showall'] = $specialist_post_info['result']['is_showall'];
//            }

            if ($row['post_type'] == 0) { // 普通贴
                // 无操作
            } else if ($row['post_type'] == 1) { // 专家贴
                $specialist_post_info = $this->get_specialist_post_info($post_id);
                $row['message'] = $specialist_post_info['return'];
                $data_content['share_desc'] = mb_substr($specialist_post_info['result']['tell_history'],0,30,'utf-8');

                $rt = $this->invitem->invite_list_db($post_id);
                $invitelist = $rt['invites'];
                $invited_ids = array_keys($invitelist);
                $data_content['all_invited'] = $invited_ids;
                $data_content['is_showall'] = $specialist_post_info['result']['is_showall'];

            } else if ($row['post_type'] == 11) { // 分享贴
                $specialist_post_info = $this->get_specialist_post_info_extend($post_id);
                $row['message'] = $specialist_post_info['return'];
                $data_content['share_desc'] = mb_substr($specialist_post_info['result']['tell_history'],0,30,'utf-8');
                $data_content['is_showall'] = $specialist_post_info['result']['is_showall'];

            } else {
                w_log('postm.php:error post_type');
            }


            $old_to_new_data = $this->oldcontent_pregmatch_index($row['message']);
            $message = $old_to_new_data['message'];
            $adds = $old_to_new_data['adds'];

            //帖子内容展示 兼容旧版本
            if(($this->pid == "2002" && version_compare($this->softversion, "1.7.0")>0) || ($this->pid == "3001" && version_compare($this->softversion, "1.7.0")>0))
            {

                //老帖子碰上新版，将老帖子分割成新帖格式
                if($adds)//老帖新版本
                {
                    $data_content['message'] = $message;
                    $note = '补充：';
                    for($add_index = 0; $add_index < 4; $add_index++ )
                    {
                        if($adds[$add_index])
                        {
                            $conent_key = 'add_content'.($add_index + 1);
                            $img_key = 'add_img_index_'.($add_index + 1);

                            $data_content[$conent_key] = $note.$adds[$add_index]['add_centent'];
                            $adds[$add_index]['index2'] = $adds[$add_index]['index2'] ? $adds[$add_index]['index2'] : $adds[$add_index]['index1'];
                            $data_content[$img_key] = $adds[$add_index]['index1'].'-'.$adds[$add_index]['index2'];
                            if($adds[$add_index]['index2'] > 0)
                            {
                                $count = (int)$adds[$add_index]['index2'] - (int)$adds[$add_index]['index1'] + 1;
                            }
                            else
                            {
                                $count = 1;
                            }

                            if ($post_imgs) {
                                $data_content[$conent_key] = $data_content[$conent_key].'(新增'.(string)$count.'张图片)';
                            } else {
                                $data_content[$conent_key] = $data_content[$conent_key];
                            }

                        }
                    }
                    //老帖新补充
                    if($row['add_content1'])
                    {
                        $this->compatible_post_join($data_content,$row,count($adds));
                    }
                }
                else//新帖新版本
                {
                    $data_content['message'] = $row['attachment'] ? $row['message']."\r\n".$row['attachment'] : $row['message'];
                    $this->new_post_join($data_content,$row);
                }
            }
            else
            {
                //新帖碰上老版本
                if($adds)//老帖老版本
                {
                    $data_content['message'] = $row['attachment'] ? $row['message']."\r\n".$row['attachment'] : $row['message'];
                }
                else//新帖老版本
                {
                    $data_content['message'] = $row['message'];
                    for ($add_index = 1; $add_index <= 4; $add_index++)
                    {
                        $conent_key = 'add_content' . $add_index;
                        $img_key = 'add_img_index_' . $add_index;

                        $indexs = explode('-', $row[$img_key]);

                        // 判断有没有图
                        if(count($indexs) > 1 && $post_imgs) {
                            //如果 只有一张图
                            if ($indexs[0] == $indexs[1]) {
                                    $add_content = '补充：' . $row[$conent_key] . '(新增第' . $indexs[0] . '张图片)';
                                // 多张图
                            } else {
                                    $add_content = '补充：' . $row[$conent_key] . '(新增第' . $indexs[0] . ' - ' . $indexs[1] . '张图片)';
                            }
                          // 没图
                        } else {
                            $add_content = '补充：' . $row[$conent_key];
                        }


                    }
                    $data_content['message'] = $row['attachment'] ? $data_content['message'] . "\r\n" . $row['attachment'] : $data_content['message'];
                }
            }

            $data_content['post_type'] = $row['post_type'];
            $data_content['typeid'] = $row['typeid'];
            $data_content['at_friend_list'] = $row['at_friend_list_id_array'] ? $this->get_friend_list($row['at_friend_list_id_array']) : ""; //如果没有  就是 空
            $data_content['addtime'] = $row['create_time'] ? $row['create_time'] : $row['addtime'];
            $data_content['create_time'] = $row['create_time'];
            $data_content['addtime_cmdate'] = cgmdate($data_content['addtime'],'Y-m-d H:i:s');
            $data_content['comment_addtime'] = $row['addtime'] ? $row['addtime'] : $row['create_time'];

            $data_content['sharepic'] = $sharepic_imgs[0];
            $data_content['favorite_count'] = (string)$favorite_count;
            $data_content['favorite_status'] = $favorite_status;
            //$this->cache->save('searchdata_' . $post_id,$data_content,7200);
            //iPhone 1.8.1开始，补充内容放数组返回

            $add_contents = array();
            $add_img_indexs = array();
            for ($add_index = 1; $add_index <= 4; $add_index++)
            {
                $content_key = 'add_content'.$add_index;
                $img_key = 'add_img_index_'.$add_index;

                if($data_content[$content_key] )
                {
                    $add_contents[] = $data_content[$content_key];
                    $add_img_indexs[] = $data_content[$img_key];
                }
            }

            if($add_contents)
            {
                $data_content['add_contents'] = $add_contents;
                $data_content['add_img_indexs'] = $add_img_indexs;
            }

            $post_id = $row['id'];
            if($row['answer_index']&&$row['answer_index'] >0)
            {
                $data_content['have_answer'] = 1;
            }
            else
            {
                $answer = $this->commentm->get_post_answer($post_id);
                if($answer)
                {
                    $data_content['have_answer'] = 1;
                }
            }

            $data_content['is_top'] = $row['is_top'];

            //实名
            if($row['is_show_truename'] == 1)
            {
                if($row['truename'] && strcmp($row['truename'], $row['author_name']) != 0)
                {
                    $data_content['author_name'] = $row['truename'].'「'.$row['author_name'].'」';
                }
            }

            //认证用户展示医院
            if($row['verified_status'] == 3)
            {
                //取认证医院
                $verified_info = $this->userm->verified_info($row['author_id']);
                $hospital =  $verified_info['hospital'];
                if(!$hospital)
                {
                    $hospital = $row['practice_hospital'];
                }
                $data_content['practice_hospital'] = $hospital;
                if(version_compare($this->softversion, '1.9.3') <= 0) {
                    $data_content['thread_name'] = $hospital . ' ' . $data_content['thread_name'];
                }
                else
                {
                    if(is_numeric($row['post_title']))
                    {
                        ci_load_once('posttitlem');
                        $row['post_title'] = $this->posttitlem->getPosttitleName($row['post_title']);
                    }
                    $data_content['thread_name'] = $data_content['thread_name'].' '.$row['post_title'];
                }
            }

            $data_content["paid_success"] = $row["paid_success"];
            $data_content["thread"] = $row["thread"];
            $data_content["post_type_extend"] = $row["post_type_extend"];
            $data_content["is_pinpai"] = $row["is_pinpai"];
            # 获取投票帖选项
            if(isset($row['post_type_extend']) && $row['post_type_extend'] == 5)
            {
                $data_content['option'] = $this->get_vote_list($post_id);
                $data_content['total_count'] = $this->get_total_count($post_id);
                $data_content['click_num'] = $this->get_click_vote($post_id,$this->uid);
            }

            return $data_content;
        }

        /* 之前逻辑有问题，修改 */

        public function one_post_content($post_id,$cache=1)
        {
            $mc = $this->cache->memcached;
            $key = self::MC_KEY_POST4SEARCH . $post_id;
            if(!$this->cache->memcached->is_supported())
            {
                $result = array("code" => -3,'tips' => "缓存未开启");
            }
            if($cache == 1)
            {
                $row = $mc->get($key);
            }
            if($cache == 0 || !$row) {
                $this->db->select('ml_post.*,ml_thread.thread_name,ml_fellow.thread AS thread,ml_fellow.username AS author_name,ml_fellow.head_ico AS head_ico,ml_fellow.verified_status AS verified_status,ml_fellow.admin_level as admin_level,ml_fellow.user_level as user_level,ml_fellow.is_show_truename as is_show_truename,ml_fellow.truename as truename,ml_fellow.practice_hospital as practice_hospital, ml_fellow.post_title as post_title')->from('ml_post');
                $this->db->join('ml_fellow', 'ml_post.author_id=ml_fellow.id', "left");
                $this->db->join('ml_thread', 'ml_fellow.thread=ml_thread.id', "left");
                $this->db->where('ml_post.id', $post_id);
                $this->db->where('ml_post.is_show', 1);
                $query = $this->db->get()->result_array();

                if ($query && $query[0]) {
                    $row = $query[0];
                    $mc->save($key,$row,20*60);
                } else {
                    return array();
                }
            }
            return $row;
        }

        public function get_specialist_post_info($post_id)
        {
            $result = $this->db->select("tell_history,check_body,analysis_check,tentative_diagnosis,questions,is_showall")->where("pid", $post_id)->get("ml_post_specialist")->result_array();
            $return = '';
            $return .= '<h5>【主诉及病史】</h5>';
            $return .= $result[0]['tell_history'];
            $return .= '<h5>【查体】</h5>';
            $return .= $result[0]['check_body'];
            $return .= '<h5>【化验及检查】</h5>';
            $return .= $result[0]['analysis_check'];
            $return .= '<h5>【初步诊断】</h5>';
            $return .= $result[0]['tentative_diagnosis'];
            $return .= '<h5>【会诊问题】</h5>';
            $return .= $result[0]['questions'];
            return $return = array('return' => $return, 'result' => $result[0]);
        }

        public function get_specialist_post_info_extend($post_id)
        {
            $params = 'tell_history,check_body,analysis_check,tentative_diagnosis,is_showall';
            $result = $this->db
                ->select($params)
                ->where("pid",$post_id)
                ->get("ml_post_specialist")
                ->result_array();
            $params = $this->db->select('age,sex')->from('ml_post')->where('id', $post_id)->get()->result_array();
            $return = '';
            if ($params[0]['age'] !== '' && !empty($params[0]['sex'])) {
                if ($params[0]['sex'] == 1) {
                    $return .= "患者性别：男，年龄：" . $params[0]['age'] . "。\n";
                } elseif ($params[0]['sex'] == 2) {
                    $return .= "患者性别：女，年龄：" . $params[0]['age'] . "。\n";
                }
            }
            $return .= "【主诉及病史】\n";
            $return .= $result[0]['tell_history']."\n";
            $return .= "【查体】\n";
            $return .= $result[0]['check_body']."\n";
            $return .= "【化验及检查】\n";
            $return .= $result[0]['analysis_check']."\n";
            $return .= "【诊断或问题】\n";
            $return .= $result[0]['tentative_diagnosis'];
            return $return = array('return'=>$return,'result'=>$result[0]);
        }

        public function oldcontent_pregmatch_index($message)
        {
            $splits = explode('补充：',$message);
            $index_regex = '/补充：([.\S\s]*?)\(新增第(\d+?)( - 第(\d+?))?图片\)/i';
            preg_match_all($index_regex, $message, $mat);
            $adds = array();
            for ($i = 0; $i < count($mat[0]); $i++) {
                $add_info = array();
                $add_info['add_centent'] = $mat[1][$i];
                $add_info['index1'] = $mat[2][$i];//$mat[2]第二个括号提取结果
                $add_info['index2'] = $mat[4][$i];//$mat[4]第四个括号提取结果
                $adds[] = $add_info;
            }
            $result = array();
            $result['adds'] = $adds;
            $result['message'] = $splits[0];
            return $result;
        }

        //获取专家会诊贴内容

        public function compatible_post_join(&$data_content, &$row,$offset=0)//$offset是为老帖新补充准备的，老帖message中能解析出补充来，新补充后add_content1等上也有数据，所以得做偏移
        {
            $answer_index = $row['answer_index'];

            for($add_index = 1; $add_index <= 4; $add_index++ )
            {
                $conent_key = 'add_content'.$add_index;
                $img_key = 'add_img_index_'.$add_index;

                $offset_content_key = 'add_content'.($add_index +$offset);
                $offset_img_key = 'add_img_index_'.($add_index + $offset);

                $indexs = explode('-', $row[$img_key]);
                $count = $indexs[1] - $indexs[0] + 1;

                $note = '';
                if($answer_index && ($answer_index == $add_index))//作者已经添加了答案
                {
                    $note = '答案：';
                    if(($this->pid == "2002" && version_compare($this->softversion, "1.9.0")<0) || ($this->pid == "3001" && version_compare($this->softversion, "1.9.0")<0))
                    {
                        $default_img = 'http://static.medical-lighter.com/publicimage/default_content.jpg';
                        $my_img_key = 'add_img_index_'.$answer_index;
                        if(0 == strcmp($row[$my_img_key], '0-0'))
                        {
                            $data_content['post_imgs'][] = $default_img;
                            $img_count = count($data_content['post_imgs']);
                            $row[$offset_img_key] = $img_count.'-'.$img_count;
                        }
                        else
                        {
                            $row[$offset_img_key] = $row[$img_key];
                        }
                    }
                    else{
                        $row[$offset_img_key] = $row[$img_key];
                    }
                }
                else
                {
                    $note = '补充：';
                    $row[$offset_img_key] = $row[$img_key];
                }

                if($row[$conent_key])
                {
                    $data_content[$offset_content_key] = $note.$row[$conent_key];
                    if($indexs[1] > 0 && $indexs[0] > 0)
                    {
                        $data_content[$offset_content_key] .= '(新增'.$count.'张图片)';
                    }
                    $data_content[$offset_img_key] = $row[$offset_img_key];
                }
            }
        }

        public function new_post_join(&$data_content, &$row)
        {
            $answer_index = $row['answer_index'];

            for($add_index = 1; $add_index <= 4; $add_index++ )
            {
                $conent_key = 'add_content'.$add_index;
                $img_key = 'add_img_index_'.$add_index;
                if(!$row[$img_key])
                {
                    continue;
                }
                $indexs = explode('-', $row[$img_key]);
                $count = $indexs[1] - $indexs[0] + 1;

                $note = '';
                if($answer_index && ($answer_index == $add_index))//作者已经添加了答案
                {
                    $note = '答案：';
                    if(($this->pid == "2002" && version_compare($this->softversion, "1.9.0")<0) || ($this->pid == "3001" && version_compare($this->softversion, "1.9.0")<0))
                    {
                        $default_img = 'http://static.medical-lighter.com/publicimage/default_content.jpg';
                        $my_img_key = 'add_img_index_'.$answer_index;
                        if(0 == strcmp($row[$my_img_key], '0-0'))
                        {
                            $data_content['post_imgs'][] = $default_img;
                            $img_count = count($data_content['post_imgs']);
                            $row[$my_img_key] = $img_count.'-'.$img_count;
                        }
                    }

                    if($this->pid == "3001" &&version_compare($this->softversion, "1.9.4") >= 0)
                    {
                        $my_img_key = 'add_img_index_'.$answer_index;
                        if(0 == strcmp($row[$my_img_key], '0-0'))
                        {
                            $row[$my_img_key] = '';
                        }
                    }
                }
                else
                {
                    $note = '补充：';
                }

                if($row[$conent_key])
                {
                    $data_content[$conent_key] = $note.$row[$conent_key];
                    if($indexs[1] > 0 && $indexs[0] > 0)
                    {
                        // v2.1 没有图片去掉提示 （新增。。。图片）
                        if (version_compare($this->softversion, "2.1.0") >=0) {
                            if ($count) {
                                $data_content[$conent_key] .= '(新增'.$count.'张图片)';
                            }
                        } else {
                            $data_content[$conent_key] .= '(新增'.$count.'张图片)';
                        }

                    }
                    $data_content[$img_key] = $row[$img_key];
                }
            }
        }

        public function get_friend_list($at_friend_list_id_array)
        {
            $at_friend_list_id_array = json_decode($at_friend_list_id_array,2);
            $at_friend_name_list = "@";
            if(is_array($at_friend_list_id_array) && isset($at_friend_list_id_array))
            {
                foreach ($at_friend_list_id_array as $id_value) {
                    $userinfo = $this->userm->get_one_user_4_search($id_value,$this->uid);
                    $at_friend_name_list = $at_friend_name_list.$userinfo['username'].",";
                }
                $at_friend_name_list = rtrim($at_friend_name_list,",");
            }
            else
            {
                $at_friend_name_list = "";
            }

            return $at_friend_name_list;
        }

        /**
         * 获取投票选项以及数量
         * @param $post_id
         * @param int $cache
         * @return array|mixed
         */
        public function get_vote_list($post_id, $cache = 1)
        {
            $key = VOTE_OPTION_NUM_PREFIX.$post_id;
            $res = unserialize($this->redis->get($key));
            if (!$res || $cache == 0) {
                $res = $this->db->select('id,option,count,sort')->from('ml_vote_option')->where('post_id', $post_id)->order_by('sort')->get()->result_array();
                if ($res) $this->redis->save($key, serialize($res), POST_INFO_STRING_KEY_EXPIRE_TIME);
            }

            return $res;
        }

        /**
         * 获取投票总数量
         * @param $post_id
         * @return int|mixed
         */
        public function get_total_count($post_id, $cache = 1)
        {
            $key = VOTE_NUM_PREFIX . $post_id;
            $count = $this->redis->get($key);
            if ($count === false || $cache == 0) {
                $res = $this->db->select_sum('count')->from('ml_vote_option')->where('post_id', $post_id)->get()->row_array();
                $count = (int)$res['count'];
                $this->redis->save($key, $count, POST_INFO_STRING_KEY_EXPIRE_TIME);
            }
            return (string)$count;
        }

        /**
         * 判断用户 是否有 投票选项
         * @param $post_id
         * @param $author_id
         * @return mixed
         */
        public function get_click_vote($post_id,$author_id)
        {
            $filter = array('clicker_id' => $author_id, 'post_id' => $post_id);
            $res = $this->db->select('option_id')->from('ml_vote_relation')->where($filter)->get()->row_array();
            if (!$res) return NULL; // 这里必须为NULL,客户端做了处理
            return (string)$res['option_id'];
        }
        
        public function get_all_post_id_list($user_id,$page,$page_size,$order=0,$post_type_extend=0, $hate_info = array())
        {
            $start = ($page-1)*$page_size;
            switch($order)
            {
                case 1:
                    $order_by = "visit_number";
                    break;
                case 2:
                    $order_by = "favorite_count";
                    break;
                case 3:
                    $order_by = "comment_count";
                    break;
                default:
                    $order_by = "id";
                    break;
            }

            // 屏蔽用户及帖子
            if (isset($hate_info['hate_ids']) && $hate_info['hate_ids']) {
                $this->db->where_not_in('id', $hate_info['hate_ids']);
            }
            if (isset($hate_info['hate_user']) && $hate_info['hate_user']) {
                $this->db->where_not_in('author_id', $hate_info['hate_user']);
            }

            if(isset($post_type_extend) && $post_type_extend){
                if($post_type_extend == 2 || $post_type_extend == 3){
                    # 疑难求助及快速求助数据合并
                    $all_post_id_list = $this->db->select("id")->from("ml_post")->where(array("is_show"=>1,"is_top"=>0,'post_type_extend'=>2))->or_where('post_type_extend',3)->order_by($order_by,"desc")->limit($page_size,$start)->get()->result_array();
                }else{
                    $all_post_id_list = $this->db->select("id")->from("ml_post")->where(array("is_show"=>1,"is_top"=>0,'post_type_extend'=>$post_type_extend))->order_by($order_by,"desc")->limit($page_size,$start)->get()->result_array();
                }
                if($post_type_extend == 100){
                    # 品牌贴列表
                    if ($this->uid) {
                        $all_post_id_list = $this->db->select("id")->from("ml_post")->where(array("is_show" => 1, "is_top" => 0, 'is_pinpai' => 2))->order_by($order_by, "desc")->limit($page_size, $start)->get()->result_array();
                    } else {
                        $all_post_id_list = $this->db->select("id")->from("ml_post")->where(array("is_show" => 1, "is_top" => 0, 'is_pinpai' => 2))->where_in('post_type_extend', array(1, 2, 3))->order_by($order_by, "desc")->limit($page_size, $start)->get()->result_array();
                    }
                }
                }else{

                $all_post_id_list = $this->db->select("id")->from("ml_post")
                    ->where(array("is_show"=>1,"is_top"=>0, 'post_type<>' => 1))
                    ->where_not_in('post_type_extend', array(4,5))
                    ->order_by($order_by,"desc")
                    ->limit($page_size,$start)
                    ->get()->result_array();
            }
            $post_normal_id_list = array();
            foreach ($all_post_id_list as $value) {
                $post_normal_id_list[] = $value['id'];
            }
            return $post_normal_id_list;
        }
        
        /*
         * no_qv 2.2 我的回帖过滤文字问答及投票
         */

        /* 获取订阅帖子列表 */
        public function get_rss_post_id_list_2_2($user_id, $page, $page_size, $order = 0, $post_type_extend = 0, $hate_info = array())
        {
            //判断用户是否订阅过   如果订阅过
            if (!$this->uid) {
                //品牌贴列表
                $rss_post_array = $this->get_brand_post_no_login($page, $page_size);
            } else {
                //登录状态
                $rss_post_array = $this->rssm->get_user_rss_array_for_2_2($user_id, $post_type_extend, $page, $page_size, $order, $hate_info);
            }
            return $rss_post_array;
        }


        /* 获取品牌贴(登录及未登录情况) */
        public function get_brand_post_no_login($page, $page_size)
        {
            $start = ($page - 1) * $page_size;
            $query = 'SELECT id FROM ml_post
                          WHERE  is_pinpai =2 and post_type_extend in (1,2,3)
                          and is_show =1 order by id desc
                          limit ' . ($start ? $start . ', ' : '') . $page_size;
            $result = $this->db->query($query)->result_array();
            $post_normal_id_list = array();
            foreach ($result as $value)
            {
                $post_normal_id_list[] = $value['id'];
            }
            return $post_normal_id_list;
        }


        public function get_rss_post_id_list($user_id, $page, $page_size, $order = 0)
        {
            //判断用户是否订阅过   如果订阅过
            $rss_status_array = $this->rssm->get_user_rss_array($user_id);
            $rss_keyword_array = array();
            if ($rss_status_array) {
                foreach ($rss_status_array as $rss_value) {
                    $rss_keyword_array[] = $rss_value;
                }
            } else {
                $user_info = $this->userm->getUserInfoById($user_id);
                $thread = $user_info['thread'];
                $rss_keyword_array[] = $thread;
            }
            //如果有订阅走搜索  没有没有 直接空数组
            $post_normal_id_list = array();
            if ($rss_keyword_array) {
                $start = ($page - 1) * $page_size;
                switch ($order) {
                    case 1:
                        $order_by = "visit_number";
                        break;
                    case 2:
                        $order_by = "favorite_count";
                        break;
                    case 3:
                        $order_by = "comment_count";
                        break;
                    default:
                        $order_by = "id";
                        break;
                }

                // 先去redis缓存,不存在取库
                $this->load->model('redism');
                $post_normal_id_list = $this->redism->get_rss_post_ids($user_id, $page, $page_size, $order_by);
                if (!$post_normal_id_list) {
                    //$query = 'SELECT DISTINCT ml_posttype.post_id FROM ml_posttype LEFT JOIN ml_post on ml_post.id = ml_posttype.post_id WHERE ml_posttype.type_id IN ('.implode(',', $rss_keyword_array).') and ml_posttype.count > 0 order by ml_post.'.$order_by.' desc limit '.($start ? $start.', ' : '').$page_size;
                    $query = 'SELECT DISTINCT ml_posttype.post_id FROM ml_posttype,ml_post WHERE  ml_posttype.count > 0 AND ml_posttype.type_id IN (' . implode(',', $rss_keyword_array) . ') and ml_posttype.post_id=ml_post.id order by ml_post.' . $order_by . ' desc limit ' . ($start ? $start . ', ' : '') . $page_size;
                    if ($order_by == "addtime") {
                        $query = 'SELECT DISTINCT ml_posttype.post_id FROM ml_posttype WHERE ml_posttype.type_id IN (' . implode(',', $rss_keyword_array) . ') and ml_posttype.count > 0 order by ml_posttype.addtime desc limit ' . ($start ? $start . ', ' : '') . $page_size;
                    }
                    $result = $this->db->query($query)->result_array();
                    foreach ($result as $value) {
                        $post_id = $value['post_id'];
                        $post_normal_id_list[] = $post_id;
                    }
                }
            }
            return $post_normal_id_list;
        }

        //获取帖子分类

        function is_in_post_list($get_one_post_content)
        {
            //如果是专家会诊帖，且用户不是作者和被邀请人，则不显示
            $all_invited = $get_one_post_content['all_invited'];
            $post_type = $get_one_post_content['post_type'];
            $is_showall = $get_one_post_content['is_showall'];//运营人员选定是否展示给所有用户,0或者不存在则不展示

            //专家咨询帖，不是作者本人，不在邀请列表中，一般不显示
            if ($post_type == 1 && !in_array($this->uid, $all_invited) && $this->uid != $get_one_post_content['author_id']) {
                //但如果运营人员手工打开，则可以展示给全用户
                if (!$is_showall) {
                    return false;
                }
            }
            //如果帖子还未支付，不展示给专家
            if ($post_type == 1 && $get_one_post_content['paid_success'] != 1 && $this->uid != $get_one_post_content['author_id']) {
                return false;
            }
            return true;
        }

        /* 获取标签列表 */

        public function array_sort($array, $key1, $key2, $sort = False)
        {
            if (!$sort)
            {
                $sort = 'DESC';
            }
            if (is_array($array)) {
                $key_array = array();
                $new_array = array();
                $new_array1 = array();
                foreach ($array AS $av)
                {
                    $key_array[$av[$key2]] = $av[$key1];
                    $new_array1[$av[$key2]] = $av;
                }
                if ($sort == 'DESC') {
                    uasort($key_array, array($this, 'cmp'));
                }
                foreach ($key_array as $k => $v) {
                    $new_array[] = $new_array1[$k];
                }
                unset($key_array);
                return $new_array;
            } else {
                return $array;
            }
        }

        //获取帖子分类 for 发帖时
        public function get_top_post_id($device_code)
        {
            $mc = $this->cache->memcached;
            $this->cache->memcached->is_supported();
            $key = self::MC_KEY_TOP_POST_KEY . $device_code;
            $top_id = $mc->get($key);
            if (!$top_id)
            {
                $device_code = $device_code == "3001" ? 3 : 2;
                $where = "is_show=1 and is_top=1 and (top_device=1 or top_device=" . $device_code . ")";
                $top_post_id_list = $this->db->select("id")->from("ml_post")->where($where)->order_by("id", "desc")->limit(1, 0)->get()->result_array();
                //echo $this->db->last_query();
                $top_id = $top_post_id_list[0]['id'];
                if (!$top_id)
                {
                    $top_id = 0;
                }
                $mc->save($key, $top_id, 30 * 60);
            }
            return $top_id;
        }
        
        //获取分类名称

        public function get_digest_post_list($page_size,$page)
        {
            $start = ($page-1)*$page_size;
            $all_post_id_list = $this->db->select("id")->from("ml_post")->where(array("is_show"=>1,"digest"=>1))->order_by("addtime","desc")->limit($page_size,$start)->get()->result_array();
            $post_normal_id_list = array();
            foreach ($all_post_id_list as $value) {
                $post_normal_id_list[] = $this->get_one_post_4_search($value['id'],$this->uid);
            }

            return $post_normal_id_list;
        }
        
        //获取用户回复的帖子数

        public function get_digest_thread_post_list($thread, $page_size, $page)
        {
            $mc = $this->cache->memcached;
            $key = 'get_digest_thread_post_list_2' . (string)$page . $page_size . $this->uid;
            $post_normal_id_list = $mc->get($key);
            if ($post_normal_id_list) return $post_normal_id_list;

            $start = ($page-1)*$page_size;

            if($thread == -1 || $thread == -2)
            {
                $where = "(is_show=1 and digest=1 and post_type=0)";
                $all_post_id_list = $this->db->select("id")->from("ml_post")->where($where)->order_by("id", "desc")->limit($page_size, $start)->get()->result_array();
            }
            else
            {
                $where = "a.is_show=1 and a.digest=1 and b.type_id in (" . $thread . ') and b.type =1';
                $all_post_id_list = $this->db
                    ->select("a.id")
                    ->from("ml_post as a")
                    ->join('ml_posttype as b', 'a.id = b.post_id', 'left')
                    ->where($where)
                    ->group_by('a.id')
                    ->order_by("id", "desc")
                    ->limit($page_size, $start)
                    ->get()
                    ->result_array();
            }
            $post_normal_id_list = array();
            foreach ($all_post_id_list as $value) {
                $post_normal_id_list[] = $this->get_one_post_4_search($value['id'],$this->uid);
            }
            $mc->save($key, $post_normal_id_list, 60*3);
            return $post_normal_id_list;
        }
        
        
        //获取用户列表

        public function get_digest_thread_list($thread, $page_size,$page,$order=0,$dis_cate_flag=0)
        {
            $mc = $this->cache->memcached;
            if(!$this->cache->memcached->is_supported()) {
                $result = array("code" => -3,'tips' => "缓存未开启");
            }
            $key = 'get_digest_thread_post_list_2'.(string)$page.$page_size.$thread.$this->uid.'_'.$order;
            $post_normal_id_list = $mc->get($key);
            /*if($post_normal_id_list) {
                return $post_normal_id_list;
            }*/
            $start = ($page-1)*$page_size;
            switch($order) {
                case 1:
                    $order_column = 'visit_number';
                    break;
                case 2:
                    $order_column = 'favorite_count';
                    break;
                case 3:
                    $order_column = 'comment_count';
                    break;
                default:
                    $order_column = 'lastpost';
                    break;
            }
            if($thread == -1 || $thread == -2) {
                $where = "(is_show=1 and digest=1 and post_type=0)";
                $all_post_id_list = $this->db
                    ->select("a.post_id as id")
                    ->from("ml_posttype as a")
                    ->join('ml_post as b','b.id=a.post_id','left')
                    ->where(array('a.type_id'=>$thread,'a.type'=>$dis_cate_flag,'b.is_show'=>1,'b.digest'=>1,'b.post_type'=>0))
                    ->order_by("b.".$order_column,"desc")
                    ->limit($page_size,$start)
                    ->get()
                    ->result_array();
            }
            else
            {
                $all_post_id_list = $this->db
                    ->select("a.post_id as id")
                    ->from("ml_posttype as a")
                    ->join('ml_post as b','b.id=a.post_id','left')
                    ->where(array('a.type_id'=>$thread,'a.type'=>$dis_cate_flag,'b.is_show'=>1,'b.digest'=>1))
                    ->order_by("b.".$order_column,"desc")
                    ->limit($page_size,$start)
                    ->get()
                    ->result_array();
            }
            $post_normal_id_list = array();
            foreach ($all_post_id_list as $value) {
                //$post_normal_id_list[] = $this->get_one_post_4_search($value['id'],$this->uid);
                $post_normal_id_list[] = $this->get_one_post_info($value['id'], 1);
            }
            $mc->save($key, $post_normal_id_list, 60*3);
            return $post_normal_id_list;
        }

        public function get_one_post_4_real($post_id,$observer_id)
        {
            $post = array();

            $post = $this->cache->get('searchdata_' . $post_id);
            if($post)
            {
                return $post;
            }

            $this->db->select('ml_post.*,ml_fellow.username AS author_name,ml_fellow.verified_status AS verified_status,ml_fellow.admin_level as admin_level,,ml_fellow.user_level as user_level')->from('ml_post');
            $this->db->join('ml_fellow','ml_post.author_id=ml_fellow.id');
            $this->db->where('ml_post.id',$post_id);
            $this->db->where('ml_post.is_show',1);
            $query = $this->db->get()->result_array();
            if($query && $query[0])
            {
                $row = $query[0];
            }else
            {
                return array();
            }

            $post_imgs = array();
            $sharepic_imgs = array();

            $post_imgs_original = $this->db->select("original,small")->where(array("pid"=>$post_id,"cid"=>0))->get("ml_attachments")->result_array();
            foreach ($post_imgs_original as $key)
            {
                $post_imgs[] = ret_fullpath_url($key['original']);
                $sharepic_imgs[] = ret_fullpath_url($key['small']);
            }
            $favorite_count = $this->favoritem->get_post_fav_count($post_id);

            //如果用户为-1  说明是没有注册 则全部显示没有收藏
            //$this->params['author_id'] = "3032";

            if(isset($this->uid) && $this->uid > 0)
            {
                $favorite_count_status = $this->favoritem->is_fav($this->uid, $post_id);
            }
            else
            {
                if($observer_id)
                {
                    $favorite_count_status = $this->favoritem->is_fav($observer_id, $post_id);
                }
                else
                {
                    $favorite_count_status = 0;
                }
            }


            $favorite_status = $favorite_count_status ? "1" : "0";


            $data_content['id'] = $post_id;
            $data_content['author_id'] = $row['author_id'];
            $data_content['verified_status'] = $row['verified_status'];
            $data_content['admin_level'] = $row['admin_level'];
            $data_content['is_expert'] = $row['user_level'] ? 1 : 0;
            $data_content['author_name'] = $row['author_name'];
            //$data_content['author_name'] = $row['admin_level'] > 2 ? "🔅".$row['author_name'] : $row['author_name'];
            $data_content['post_imgs'] = $post_imgs;
            $data_content['is_recommend'] = "0";  //是否为推荐帖子 推荐帖子 关闭时间显示
            $data_content['aspect_ratio'] = $row['aspect_ratio'];
            $data_content['comment_count'] = (string)$this->commentm->get_count_for_client($row['id']);
            $data_content['message'] = $row['attachment'] ? $row['message']."\r\n".$row['attachment'] : $row['message'];
            $data_content['typeid'] = $row['typeid'];
            $data_content['at_friend_list'] = $row['at_friend_list_id_array'] ? $this->get_friend_list($row['at_friend_list_id_array']) : ""; //如果没有  就是 空
            $data_content['addtime'] = $row['addtime'];
            $data_content['addtime_cmdate'] = cgmdate($row['addtime'],'Y-m-d H:i:s');
            $data_content['comment_addtime'] = $row['addtime'];

            $data_content['sharepic'] = $sharepic_imgs ? $sharepic_imgs[0] : "";
            $data_content['favorite_count'] = (string)$favorite_count;
            $data_content['favorite_status'] = $favorite_status;

            $this->cache->save('searchdata_' . $post_id,$data_content,7200);
            return $data_content;
        }
        //更新用户发帖数


        public function get_post_list_for_user_comment($start,$page_size,$user_id,$where,$no_qv=false)
        {
            $this->db->select('ml_comment.post_id, ml_comment.addtime');
            $this->db->from('ml_comment');
            $this->db->join('ml_post', 'ml_comment.post_id=ml_post.id','left');
            $this->db->where("ml_comment.is_show",1);
            $this->db->where("ml_post.is_show",1);
            if($this->uid != $user_id && !in_array($this->uid, [1, 14877, 31495]))
            {
                $this->db->where("ml_post.post_type",0);
            }
            /* # 2.2需求
             if($no_qv)
             {
                 $this->db->where_in('post_type_extend',array(1,2,3));
             }*/
            $this->db->where_not_in('post_type_extend', array(4, 5));
            $this->db->where("ml_comment.author_id",$user_id);
            $this->db->where($where);
            $this->db->group_by("ml_comment.post_id");
            $this->db->order_by("ml_comment.addtime","desc");
            $this->db->limit($page_size,$start);

            $post_id_array = $this->db->get()->result_array();
            w_log($this->db->last_query());
            if($post_id_array)
            {
                $post_id_string = '';
                $result = array();
                foreach($post_id_array as $val)
                {
                    //$query = pm_db::fetch_all_result("select a.id,a.post_imgs,a.aspect_ratio,a.message,a.addtime,a.author_id,b.username as author_name from ml_post as a left join ml_fellow as b on a.author_id=b.id where a.is_show=1 and a.id=".$val['post_id']."");
                    $this->db->select("ml_post.id,ml_post.post_imgs,ml_post.aspect_ratio,ml_post.message,ml_post.addtime,ml_post.author_id,ml_fellow.username as author_name");
                    $this->db->from("ml_post");
                    $this->db->join("ml_fellow","ml_post.author_id=ml_fellow.id","left");
                    $this->db->where("ml_post.is_show",1);
                    $this->db->where("ml_post.id",$val['post_id']);
                    $query = $this->db->get()->result_array();
                    //$res = $this->db->last_query();
                    //如果有结果就放入数组 否则不处理
                    w_log($this->db->last_query());
                    if($query)
                    {
                        $row = $query[0];
//                        $comment_count = $this->commentm->get_count_for_client(array("is_show"=>1,"post_id"=>$row['id']));

                        $data_content = array();
                        $data_content['id'] = $row['id'];
                        $data_content['comment_addtime'] = $val['addtime'];
                        $result[] = $data_content;
                    }

                }
            }
            else
            {
                $result = array();
            }
            return $result;

        }
        
        
        //更新用户回帖数

        public function get_type_list($parent_id = 0,$post_id,$user_id)
        {
//            $mc = $this->cache->memcached;
//            $key = 'get_type_list_'.$parent_id.'_'.$post_id.'_'.$user_id;
//            $data = $mc->get($key);
//            if($data)
//            {
//                return $data;
//            }
//            else
//            {
                 $this->load->Model("type_weightm");
                //三维数组
                $this->db->select("id,thread_name,parent_id,sort");
                $this->db->from("ml_thread");
                $this->db->where("parent_id", $parent_id);
                $this->db->order_by("sort", "asc");
                $result = $this->db->get()->result_array();
                $response_array = array();
                foreach ($result as $value) {
                    $this->db->select("id,thread_name");
                    $this->db->from("ml_thread");
                    $this->db->where("parent_id", $value['id']);
                    $this->db->order_by("sort", "asc");
                    $result_val = $this->db->get()->result_array();
                    if ($result_val) {
                        $type = array();
                        $type['id'] = $value['id'];
                        $type['name'] = $value['thread_name'];
                        $type['sort'] = $value['sort'];
                        $type['content'] = $this->get_type_list($value['id'], $post_id, $user_id);
                        $response_array[] = $type;
                    } else {
                        $type = array();
                        $type['id'] = $value['id'];
                        $type['parent_id'] = $value['parent_id'];
                        $type['sort'] = $value['sort'];
                        $type['thread_name'] = $value['thread_name'];
                        //获取分类过
                        $type['type_weight_count'] = $this->type_weightm->type_id_count($post_id,$value['id']);
                        //获取用户分类状态
                        $action_count = $this->type_weightm->get_action_count(array("post_id" => (int)$post_id, "type_id" => (int)$value['id'], "user_id" => $user_id));
                        $type['action_count'] = $action_count[0]["action_count"];
                        $response_array[] = $type;
                    }
                }
//            }
//            $mc->save($key,$response_array,2*60);

            return $response_array;

        }
        
        //更新帖子分类

        public function get_all_tag_list($page,$page_size)
        {
            $start = ($page-1)*$page_size;
            $all_tag_list = $this->db
                ->select("id,tag_name")
                ->from("ml_tags")
                ->order_by("sort","desc")
                ->limit($page_size,$start)
                ->get()
                ->result_array();
            return $all_tag_list;
        }
        
        
        //更新用户发帖数(添加)

        public function get_type_list_1_8_0($parent_id = 0)
        {
            $mc = $this->cache->memcached;
            $key = 'get_type_list_1_8_0'.$parent_id;
            $data = $mc->get($key);
            if($data)
            {
                return $data;
            }
            else {
                //$this->load->Model("tmm");
                //三维数组
                $this->db->select("id,thread_name,parent_id,sort");
                $this->db->from("ml_thread");
                $this->db->where("parent_id", $parent_id);
                $this->db->order_by("sort", "asc");
                $result = $this->db->get()->result_array();
                $response_array = array();
                foreach ($result as $value) {
                    $this->db->select("id,thread_name");
                    $this->db->from("ml_thread");
                    $this->db->where("parent_id", $value['id']);
                    $this->db->order_by("sort", "asc");
                    $result_val = $this->db->get()->result_array();
                    if ($result_val) {
                        $type = array();
                        $type['id'] = $value['id'];
                        $type['name'] = $value['thread_name'];
                        $type['sort'] = $value['sort'];
                        $type['content'] = $this->get_type_list_1_8_0($value['id']);
                        $response_array[] = $type;
                    }
                    else
                    {
                        $type = array();
                        $type['id'] = $value['id'];
                        $type['parent_id'] = $value['parent_id'];
                        $type['sort'] = $value['sort'];
                        $type['thread_name'] = $value['thread_name'];
                        //获取分类过
                        $type['type_weight_count'] = 0;
                        //获取用户分类状态0
                        $type['action_count'] = 0;
                        $response_array[] = $type;
                    }
                }
            }
            $mc->save($key,$response_array,2*60);
            return $response_array;

        }
        
        //更新用户发帖数(减少)

        public function get_type_name($post_type_id)
        {
            $result = $this->db->select("thread_name,sort")->from("ml_thread")->where(array("id"=>$post_type_id))->get()->result_array();
            return $result;
        }
        
        
        
        //获取帖子状态

        public function get_comment_post_count($user_id,$no_qv=false)
        {
            $this->db->select('ml_comment.post_id, ml_comment.addtime');
            $this->db->from('ml_comment');
            $this->db->join('ml_post', 'ml_comment.post_id=ml_post.id','left');
            $this->db->where("ml_comment.is_show",1);
            $this->db->where("ml_post.is_show",1);
            if($this->uid != $user_id && $this->uid != 31495)
            {
                $this->db->where("ml_post.post_type <> ", 1);
                // 4：问答    5：投票    6：专家咨询帖
                $this->db->where_not_in('ml_post.post_type_extend', array(4, 5, 6));
            }
            $this->db->where_not_in('ml_post.post_type_extend', array(4, 5));
            $this->db->where("ml_comment.author_id",$user_id);
            $this->db->group_by("ml_comment.post_id");
            $this->db->order_by("ml_comment.addtime","desc");

            $post_id_array = $this->db->get()->result_array();
            if($post_id_array)
            {
                return count($post_id_array);
            }
            else
            {
                return 0;
            }
        }
        
        //获取帖子的发帖人id

        public function get_user_list()
        {
            return $this->db->select("id,username")->from("ml_fellow")->get()->result_array();
        }
        
        //获取帖子的发帖人信息

        public function update_user_post_count($post_count,$user_id)
        {
            $this->db->set('post_count', $post_count);
            $this->db->where("id",$user_id);
            return $this->db->update('ml_fellow');
        }
        
        //获取帖子的第一张图片

        public function update_user_comment_count($comment_count,$user_id)
        {
            $this->db->set('comment_count', $comment_count);
            $this->db->where("id",$user_id);
            return $this->db->update('ml_fellow');
        }
        
        //添加帖子

        public function update_post_type_id($post_id,$post_type_id)
        {
            $this->db->set("typeid",$post_type_id);
            $this->db->where("id",(int)$post_id);
            $result = $this->db->update('ml_post');
            //echo $this->db->last_query();
            return $result;
        }
        
        //更新帖子内容

        public function inc_post_num_for_fellow($user_id)
        {
            $this->db->set('post_count', 'post_count+1', FALSE);
            $this->db->where(array("id"=>(int)$user_id));
            $result = $this->db->update("ml_fellow");
            //echo $this->db->last_query();
            return $result;
        }

        public function dec_post_num_for_fellow($user_id)
        {
            $this->db->set('post_count', 'post_count-1', FALSE);
            $this->db->where(array("id"=>(int)$user_id));
            $result = $this->db->update("ml_fellow");
            return $result;
        }
        
        //获取帖子原有图片

        public function get_post_author_id($post_id)
        {
            $this->db->from("ml_post");
            $this->db->where(array("id"=>(int)$post_id));
            $result = $this->db->get()->result_array();
            return $result[0]['author_id'];
        }
        
        public function get_post_author_for_report($post_id)
        {
            $mc = $this->cache->memcached;
            $key = 'get_post_author_for_report'.$post_id;

            $this->cache->memcached->is_supported();

            $row = $mc->get($key);
            if($row)
            {
                return $row;
            }
            $this->db->select('ml_post.*,ml_fellow.username AS author_name,ml_fellow.email AS email,ml_fellow.user_level AS user_level,ml_fellow.id AS author_id ')->from('ml_post');
            $this->db->join('ml_fellow','ml_post.author_id=ml_fellow.id');
            $this->db->where('ml_post.id',$post_id);
            $query = $this->db->get()->result_array();
            if($query && $query[0])
            {
                $row = $query[0];
                $mc->save($key,$row, 5*60);
            }else
            {
                return array();
            }
            return $row;
        }
        
        
        //提交举报

        public function get_post_first_img($post_id)
        {
            //获取帖子的所属类型  除了投票和问答外 其他帖子都有图
            $info = $this->db->select('post_type_extend')->where('id', $post_id)->from('ml_post')->get()->row_array();
            if ($info['post_type_extend'] != 4 && $info['post_type_extend'] != 5)
            {
                $this->db->from("ml_attachments");
                $this->db->where(array("sort"=>1,"pid"=>(int)$post_id,"cid"=>0));
                $result = $this->db->get()->result_array();
                $img_array = $result[0]['small'];
            }
            elseif ($info['post_type_extend'] == 4) {
                $img_array = Postm::POST_IMG_ANSWER;
            }
            elseif ($info['post_type_extend'] == 5) {
                $img_array = Postm::POST_IMG_VOTE;
            }

            return $img_array;
        }
        
        //提交举报删除日志

        public function insert_post($data)
        {
            $result = $this->db->insert("ml_post",$data);
            if($result)
            {
                $return = $this->db->insert_id();
            }
            else
            {
                $return = false;
            }
            return $return;
        }
        
        
        //获取帖子表里的 type_id

        public function update_post($query,$data)
        {
            return $result = $this->db->where($query)->update("ml_post",$data);
        }
        
        /**
         * @param $post_id
         * @return bool
         */
        public function delete_post($post_id)
        {
            $this->load->model('clear_cachem');
            $this->clear_cachem->clear_post($post_id);

            $is_show = $this->get_post_status($post_id);
            if($is_show == 1)
            {
                $this->db->set(array("is_show"=>0))->where(array("id"=>$post_id))->update("ml_post");
                return true;
            }
            else
            {
                return false;
            }
        }
        /*
         public function get_post_id_user_thread($user_id)
         {
         $this->db->select("ml_digest_log.post_id,ml_digest_log.addtime");
         $this->db->from("ml_digest_log");
         $this->db->join("ml_fellow","ml_digest_log.thread=ml_fellow.thread","left");
         $this->db->order_by("ml_digest_log.addtime","desc");
         $this->db->where(array("ml_fellow.id"=>$user_id,"ml_digest_log.is_show"=>1));
         $return = $this->db->get()->result_array();
         if($return)
         {
         return $return[0];
         }
         else
         {
         return array();
         }
         }*/
        
        //获取一个帖子的所有参与者  包括楼主 和下面的回复人

        public function get_post_status($post_id)
        {
            $this->db->from("ml_post");
            $this->db->where(array("is_show"=>1,"id"=>(int)$post_id));
            $result = $this->db->get()->result_array();
            return $return = count($result) ? true : false;
        }
        
        
        //获取所有的帖子

        public function get_old_info($post_id)
        {
            //
            $result = $this->db->where(array("id"=>$post_id))->get("ml_post")->result_array();
            return $result[0];
        }
        
        public function get_post_image_count($post_id)
        {
            $query = $this->db->select("COUNT(*) AS num")->from('ml_attachments')->where('pid',$post_id)->where('cid',0)->get()->result_array();
            return $query && $query[0]['num'] ? $query[0]['num'] : 0;
        }
        
        public function insert_report($query)
        {
            return $this->db->insert("ml_report",$query);
        }

        public function insert_leader_del($data)
        {
            $query['post_id'] = $data['post_id'];
            $query['report_content'] = $data['report_content'];
            $query['type_id'] = $data['type_id'];
            $query['adduser'] = $data['adduser'];
            $query['addtime'] = $data['addtime'];
            return $this->db->insert("ml_del_post_info",$query);
        }

        public function get_post_typeid($post_id)
        {
            $this->db->from("ml_post");
            $this->db->where(array("is_show"=>1,"id"=>(int)$post_id));
            $result = $this->db->get()->result_array();
            if($result)
            {
                $return = $result[0]['typeid'];
            }
            else
            {
                $return = false;
            }
            return $return;
        }
        //下面2个是排序函数

        public function updateuserpctime($user_id,$ptime = 0,$ctime = 0)  //更新用户最新发帖时间和回复时间
        {
            if(!$user_id)
            {
                return;
            }
            if(!$ptime && !$ctime)
            {
                return;
            }
            $time = time();
            $ptime && $this->db->set('lastposttime',$time);
            $ctime && $this->db->set('lastcommenttime',$time);
            $this->db->where('id',$user_id);
            $this->db->update('ml_fellow');
        }
        
        public function get_post_comment_user($post_id,$comment_author_id)
        {
            //首先获取帖子的作者
            $post_author_result = $this->db->select("author_id")->from("ml_post")->where("id",$post_id)->get()->result_array();

            //然后获取所有评论的人的id
            $comment_author_result = $this->db->select("author_id")->from("ml_comment")->where("post_id",$post_id)->where('is_show',1)->get()->result_array();

            $all_author_result = array_merge($post_author_result,$comment_author_result);
            $all_author = array();
            foreach ($all_author_result as $value) {
                if($comment_author_id != $value['author_id']) $all_author[] = $value['author_id'];
            }
            $all_author = array_unique($all_author);
            return $all_author;
        }
        
        //更新帖子在精品表状态

        public function get_all_post($page_size,$page)
        {
            //获取该用户的所属分类下的推荐帖子 只取一条(如果有 则查找缓存  有则直接读取 没有则添加缓存 并设置过期时间 更新帖子添加时间)
            $thread_recommand_exists = 0;
            //根据每个人来生成缓存
            $post_thread = array();

            //获取用户分类
            $thread = $this->get_fellow_thread($this->uid);
            $post_thread = $this->cache->get('1csearchthread_' . $thread);
            if(!$post_thread)  //如果没有缓存  则查询数据库
            {
                $thread_recommand_post = $this->get_post_id_user_thread($this->uid);
                if($thread_recommand_post)
                {
                    /*//更新帖子发帖时间
                     $query_update_post = array("id"=>$thread_recommand_post['post_id']);
                     $data = array("addtime"=>$thread_recommand_post['end_time']);
                     $query_update_post_result = $this->update_post($query_update_post,$data);*/

                    $data_content = $this->get_one_post_4_search($thread_recommand_post['post_id'],$this->uid);

                    $data_content['message'] = $data_content['message'];
                    $data_content['addtime'] = $thread_recommand_post['end_time'];  //  不能更新帖子的发帖时间 不然所有人都会看到推荐的帖子  只能照顾懂啊第一页 不能照顾到其他页面
                    $data_content['addtime_cmdate'] = cgmdate($thread_recommand_post['end_time'],'Y-m-d H:i:s');
                    $data_content['start_time'] = $thread_recommand_post['start_time'];
                    $data_content['end_time'] = $thread_recommand_post['end_time'];

                    //$this->cache->save('csearchthread_' . $thread,$data_content,$thread_recommand_post['exist_time']);
                    $this->cache->save('csearchthread_' . $thread,$data_content,3600);
                    //生成缓存后 更新帖子在精品表状态
                    $query_update_digest_log = array("post_id"=>$thread_recommand_post['post_id']);
                    $update_digest_log_data = array("is_top"=>0);
                    $this->update_digest_log($query_update_digest_log,$update_digest_log_data);
                    $post_thread = $data_content;
                }
            }
            //获取正常帖子列表
            $post_normal_id_list = $this->get_post_normal_id_list($this->uid,$page,$page_size);

            $post_list = array();
            //如果有推荐帖子   去掉重复的
            if($post_thread)
            {
                foreach ($post_normal_id_list as $key => $value) {
                    $get_one_post_content = $this->get_one_post_4_search($value,$this->uid);
                    $now_time_exists = time();
                    /*
                     //如果不是推荐帖子 且内容不为空  并且在有效期内 需要去重 否则不需要

                     if($post_thread['start_time'] <= $now_time_exists && $post_thread['end_time'] > $now_time_exists)
                     {
                     if($value != $post_thread['id'] && $get_one_post_content) $post_list[] = $get_one_post_content;
                     }
                     else
                     {
                     if($get_one_post_content) $post_list[] = $get_one_post_content;
                     }*/
                    if($value != $post_thread['id'] && $get_one_post_content)
                    {
                        $post_list[] = $get_one_post_content;
                    }
                }
            }
            else
            {
                foreach ($post_normal_id_list as $key => $value) {
                    $get_one_post_content = $this->get_one_post_4_search($value,$this->uid);
                    if($get_one_post_content)
                    {
                        $post_list[] = $get_one_post_content;
                    }
                }
            }
            //如果是第一页 则插入推荐帖子
            if($page == 1)
            {
                //如果有推荐帖子
                if($post_thread)
                {
                    //更新帖子内容  不用缓存内容了
                    $data_content = $this->get_one_post_4_search($post_thread['id'],$this->uid);
                    $data_content['addtime'] = $post_thread['end_time'];  //  不能更新帖子的发帖时间 不然所有人都会看到推荐的帖子  只能照顾懂啊第一页 不能照顾到其他页面
                    $data_content['addtime_cmdate'] = cgmdate($post_thread['end_time'],'Y-m-d H:i:s');
                    $data_content['start_time'] = $post_thread['start_time'];
                    $data_content['end_time'] = $post_thread['end_time'];


                    $post_thread = $data_content;

                    //合并到帖子列表里
                    $thread_recommand_exists = 1;  //记录第一页是否推荐了
                    array_unshift($post_list, $post_thread);

                    //给最后结果排序
                    $post_list = $this->array_sort($post_list,"addtime","id",$sort="DESC");

                    //如果有精品推荐  并且排在最后了 则删除此贴
                    $count_post_list = count($post_list);
                    if($post_thread && $post_list[$count_post_list]['id'] == $post_thread['id'])
                    {
                        unset($post_list[$page_size]);
                        $thread_recommand_exists = 0;
                    }
                }
                $return = $post_list;
            }
            else
            {
                //记录最后的结果
                $return = array();
                if($thread_recommand_exists)
                {
                    foreach ($post_list as $key => $value) {
                        if($value['id'] != $post_thread['id']) $return[] = $value;
                    }
                }
                else
                {
                    $return = $post_list;
                }
            }
            return $return;

        }
        
        public function get_fellow_thread($user_id)
        {
            $return = $this->db->select("thread")->from("ml_fellow")->where("id",$user_id)->get()->result_array();
            return $return[0]['thread'];
        }
        
        
        //更新帖子推送的好友列表

        public function update_digest_log($query,$data)
        {
            $this->db->where($query)->update("ml_digest_log",$data);
        }
        
        //获取用户的registerID

        public function get_post_normal_id_list($user_id,$page,$page_size)
        {
            //判断用户是否订阅过   如果订阅过
            $rss_query = array("user_id"=>$user_id);
            $rss_status_array = $this->rssm->get_rss_status($rss_query);
            if($rss_status_array)
            {
                foreach ($rss_status_array as $rss_value) {
                    $rss_keyword_array[] = $rss_value['type_id'];
                }
            }

            //如果有订阅走搜索  没有没有 直接查询数据库
            if($rss_keyword_array)
            {
                $keyword = implode(" ", $rss_keyword_array);
                $post_normal_id_list = $this->searchm->getuserrss($keyword,$this->params['user_id'],$page,$page_size);
            }
            else
            {
                $start = ($page-1)*$page_size;
                $all_post_id_list = $this->db->select("id")->from("ml_post")->where(array("is_show"=>1))->order_by("addtime","desc")->limit($page_size,$start)->get()->result_array();
                $post_normal_id_list = array();
                foreach ($all_post_id_list as $value) {
                    $post_normal_id_list[] = $value['id'];
                }
            }
            return $post_normal_id_list;
        }
        
        //获取用户科室

        public function cmp($a, $b) {
            if ($a == $b) {
                return 0;
            }
            return ($a > $b) ? -1 : 1;
        }
        
        //更新帖子访问量

        public function update_at_friend_list_id_array($at_friend_list_id_array,$post_id)
        {
            return $result = $this->db->set("at_friend_list_id_array",$at_friend_list_id_array)->where("id",$post_id)->update("ml_post");
        }
        
        
        //获取所有的帖子

        public function get_registrationID($uid)
        {
            $userinfo = $this->userm->get_one_user_4_search($uid,$this->uid);
            return $userinfo['registrationID'];
        }

        public function get_thread_by_uid($uid)
        {
            $mc = $this->cache->memcached;
            $key = "get_thread_by_uid_".$uid;
            if(!$this->cache->memcached->is_supported())
            {
                $result = array("code" => -3,'tips' => "缓存未开启");
            }
            $thread = $mc->get($key);
            if($thread)
            {
                return $thread;
            }
            $this->db->select('thread');
            $this->db->from("ml_fellow");
            $this->db->where(array("id"=>$uid));
            $query = $this->db->get()->result_array();
            if($query && $query[0])
            {
                $row = $query[0];
            }else
            {
                return array();
            }
            $thread = $row['thread'];
            $save = $mc->save($key,$thread,$ttl=10);
            return $thread;
        }
        //获取一个分类下的推荐帖子

        public function post_visit_number_add($post_id)
        {
            $mc = $this->cache->memcached;
            $key = "post_visit_number_".$post_id;
            $visit_number = $mc->get($key);
            if (!$visit_number) {
                // 首次访问
                $mc->save($key, 1, $ttl = 0);
            } else {
                // 增加浏览数
                $mc->save($key,++$visit_number,$ttl=0);
            }
            $visit_number = $mc->get($key);
            // 每达10次访问量，更新到数据库
            if ($visit_number % 10 == 0) {
                $mc->save($key,0,$ttl=0);
                $this->db->set("visit_number",'visit_number+'.$visit_number.'',false)->where("id",$post_id)->update("ml_post");
            }
        }
        
        //发帖时添加帖子分类

        public function get_post_list_by_type_id($thread,$uid,$page_size,$page)
        {
            //获取该用户的所属分类下的推荐帖子 只取一条(如果有 则查找缓存  有则直接读取 没有则添加缓存 并设置过期时间 更新帖子添加时间)

            //根据每个人来生成缓存
            $post_thread = array();
            $thread_recommand_exists = 0;
            //获取该分类下的推荐帖子

            $mc = $this->cache->memcached;
            $key = 'csearchthread_'.$thread;
            $this->cache->memcached->is_supported();
            $post_thread = $mc->get($key);
            if(!$post_thread)  //如果没有缓存  则查询数据库
            {
                $thread_recommand_post = $this->get_recommend_post_by_thread($thread);
                if($thread_recommand_post)
                {
                    //更新帖子发帖时间

                    $data_content = $this->get_one_post_4_search($thread_recommand_post['post_id'],$uid);
                    $data_content['message'] = $data_content['message'];
                    $data_content['addtime'] = $thread_recommand_post['end_time'];  //  不能更新帖子的发帖时间 不然所有人都会看到推荐的帖子  只能照顾懂啊第一页 不能照顾到其他页面
                    $data_content['addtime_cmdate'] = cgmdate($thread_recommand_post['end_time'],'Y-m-d H:i:s');
                    $data_content['start_time'] = $thread_recommand_post['start_time'];
                    $data_content['end_time'] = $thread_recommand_post['end_time'];
//                    $this->cache->save('csearchthread_' . $thread,$data_content,3600);
                    $mc->save($key,$data_content,3600);
                    //生成缓存后 更新帖子在推荐表状态
                    $post_thread = $data_content;
                }
            }
            //获取正常帖子列表
            $limit = $page_size;
            $offset = ($page-1)*$limit;
            $this->load->Model('type_weightm');
            $post_normal_id_list = $this->type_weightm->get_post_type_weight_array($thread,$limit,$offset);

            $post_list = array();
            //如果有推荐帖子   去掉重复的
            if($post_thread && $post_normal_id_list && count($post_normal_id_list) > 0)
            {
                foreach ($post_normal_id_list as $key => $value) {
                    $get_one_post_content = $this->get_one_post_4_search($value['post_id'],$uid);
                    $now_time_exists = time();
                    //如果是推荐帖子 且内容不为空  并且在有效期内 需要去重 否则不需要

                    if($value['post_id'] != $post_thread['id'] && $get_one_post_content)
                    {
                        $is_in =  $this->is_in_post_list($get_one_post_content);
                        if(!$is_in)
                        {
                            continue;
                        }
                        $post_list[] = $get_one_post_content;
                    }
                }
            }
            else
            {
                foreach ($post_normal_id_list as $key => $value) {
                    $get_one_post_content = $this->get_one_post_4_search($value['post_id'],$uid);
                    if($get_one_post_content)
                    {
                        $is_in =  $this->is_in_post_list($get_one_post_content);
                        if(!$is_in)
                        {
                            continue;
                        }
                        $post_list[] = $get_one_post_content;
                    }
                }
            }
            //如果是第一页 则插入推荐帖子
            if($page == 1)
            {
                //如果有推荐帖子
                if($post_thread)
                {
                    //更新帖子内容  不用缓存内容了
                    $data_content = $this->get_one_post_4_search($post_thread['id'],$uid);
                    $data_content['addtime'] = $post_thread['end_time'];  //  不能更新帖子的发帖时间 不然所有人都会看到推荐的帖子  只能照顾懂啊第一页 不能照顾到其他页面
                    $data_content['addtime_cmdate'] = cgmdate($post_thread['end_time'],'Y-m-d H:i:s');
                    $data_content['start_time'] = $post_thread['start_time'];
                    $data_content['end_time'] = $post_thread['end_time'];
                    $data_content['is_recommend'] = "1";  //是否为推荐帖子 推荐帖子 关闭时间显示


                    $post_thread = $data_content;
                    //合并到帖子列表里
                    $thread_recommand_exists = 1;  //记录第一页是否推荐了
                    array_unshift($post_list, $post_thread);

                    //给最后结果排序
                    $post_list = $this->array_sort($post_list,"addtime","id",$sort="DESC");

                    //如果有推荐  并且排在最后了 则删除此贴
                    $count_post_list = count($post_list);
                    if($post_thread && $post_list[$count_post_list]['id'] == $post_thread['id'])
                    {
                        unset($post_list[$page_size]);
                        $thread_recommand_exists = 0;
                    }
                }
                $return = $post_list;
            }
            else
            {
                //记录最后的结果
                $return = array();
                if($thread_recommand_exists)
                {
                    foreach ($post_list as $key => $value) {
                        if($value['post_id'] != $post_thread['id']) $return[] = $value;
                    }
                }
                else
                {
                    $return = $post_list;
                }
            }
            return $return;

        }


        /* 发帖时添加标签分类 */

        public function get_recommend_post_by_thread($thread)
        {
            /*$this->db->select("ml_digest_log.post_id,ml_digest_log.addtime,ml_digest_log.thread,ml_digest_log.start_time,ml_digest_log.end_time");
             $this->db->from("ml_digest_log");
             $this->db->join("ml_fellow","ml_digest_log.thread=ml_fellow.thread","left");
             $this->db->order_by("ml_digest_log.addtime","desc");
             $this->db->where(array("ml_fellow.id"=>$user_id,"ml_digest_log.is_show"=>1));
             $return = $this->db->limit(1,0)->get()->result_array();*/

            $return = $this->db->select("post_id,addtime,thread,start_time,end_time")->where(array("thread"=>$thread,"is_show"=>1))->order_by("addtime","desc")->limit(1,0)->get("ml_digest_log")->result_array();

            $now_time = time();
            //如果有  并且在生效时间内
            if($return && ($return[0]['start_time'] <= $now_time && $return[0]['end_time'] > $now_time))
            {
                //生存时间
                $return[0]['exist_time'] = $return[0]['end_time'] - $return[0]['start_time'];
                return $return[0];
            }
            else
            {
                return array();
            }
        }



        //文字问答添加帖子分类

        public function add_post_type_by_author($post_id,$user_id,$type_weight,$addtime)
        {
            $this->load->Model("type_weightm");
            $post_type_id_array = array();  //记录帖子分类
            foreach ($type_weight as $value)
            {
                //更新权重表数量
                $post_type_id_array[] = (int)$value['type_id'];

                //更新用户行为表
                $set=array();
                $set['post_id'] = $post_id;
                $set['user_id'] = $user_id;
                $set['type_id'] = (int)$value['type_id'];
                $set['action_count'] = $value['action'];
                $set['addtime'] = time();
                $this->type_weightm->insert_post_type_weight_log($set);
            }
            //更新帖子分类信息 索引
            $post_type_id_string = $post_type_id_array ? implode(",",$post_type_id_array)."," : "";
            $this->type_weightm->add_post_type_id($post_id, $post_type_id_array);

            $index_data = array();
            $addtime = $addtime;
            $index_data['id']  = $post_id;
            $index_data['author_id'] = $user_id;
            $index_data['content']  =  $post_type_id_string;
            $index_data['datetime']  = date('Ymd',$addtime);
            $index_data['datetime_int']  = $addtime;
            # 接口出问题
            $this->load->library('indexs');
            //如果修改前帖子分类为空  并且新类别不为空  则直接添加索引
            # $indexs_result = $this->indexs->addIndex($index_data);
            //更新数据库帖子分类
//            $post_type_id_string_result = $this->postm->update_post_type_id($post_id,$post_type_id_string);

            return true;
        }


        public function add_post_tag_by_author($post_id, $tag_ids)
        {
            $data = array();
            $data['post_id'] = $post_id;
            $data['addtime'] = time();
            $data['type'] = 2;
            $data['count'] = 1;
            foreach($tag_ids as $k => $v)
            {
                $data['type_id'] =$v;
                $res = $this->db->insert('ml_posttype',$data);
            }
            return true;
        }
        //获取用户当天发帖数

        public function add_post_type_by_author_rlease($post_id,$user_id,$type_weight,$addtime)
        {
            $this->load->Model("type_weightm");
            $post_type_id_array = array();  //记录帖子分类
            foreach ($type_weight as $value)
            {
                //更新权重表数量
                $post_type_id_array[] = (int)$value['type_id'];

                //更新用户行为表
                /*$set=array();
                $set['post_id'] = $post_id;
                $set['user_id'] = $user_id;
                $set['type_id'] = (int)$value['type_id'];
                $set['action_count'] = $value['action'];
                $set['addtime'] = time();
                $this->type_weightm->insert_post_type_release_log($set);*/
            }
            //更新帖子分类信息 索引
            $post_type_id_string = $post_type_id_array ? implode(",",$post_type_id_array)."," : "";
            $index_data = array();
            $addtime = $addtime;
            $index_data['id']  = $post_id;
            $index_data['author_id'] = $user_id;
            $index_data['content']  =  $post_type_id_string;
            $index_data['datetime']  = date('Ymd',$addtime);
            $index_data['datetime_int']  = $addtime;
            $this->load->library('indexs');
            //如果修改前帖子分类为空  并且新类别不为空  则直接添加索引
            //$indexs_result = $this->indexs->addIndex($index_data);(出问题)
            $this->type_weightm->add_release_type_id($post_id, $post_type_id_array);
            return true;
        }

        //判断是否是首次发帖帖

        public function post_timeauthor_info($post_id)
        {
            $result = $this->db->select("create_time,author_id")->where(array("id"=>$post_id))->get("ml_post")->result_array();
            return $result[0];
        }
        //首帖（无论是否被删除）

        public function post_count_today_user($user_id)
        {
            $today_time =  strtotime("today");
            $post_count = (string)$this->postm->get_post_count(array("author_id"=>$user_id,"create_time >"=>$today_time,"is_show"=>1));
            return $post_count;
        }

        /**
         * 获取发帖总数
         * @param $query  where参数
         * @param array $post_type_extend where_in参数  此参数用来选取多个类别
         * @return int
         */
        public function get_post_count($query,$post_type_extend = array())
        {
            if($post_type_extend)
            {
                $post_count = $this->db->where($query)->where_in('post_type_extend', $post_type_extend)->count_all_results("ml_post");
            }
            else
            {
                $post_count = $this->db->where($query)->where_not_in('post_type_extend', array(4, 5))->count_all_results("ml_post");
            }

            return $post_count;
        }

        /**
         * 获取用户的发帖数量
         * @param $user_id
         * @param int $type 0:普通贴  1:专家咨询贴
         * @return int
         */
        public function get_user_post_total($user_id, $type = 0)
        {
            $filter = array('is_show' => 1, 'author_id' => $user_id);

            if ($type == 1) { // 专家咨询贴
                $filter['post_type'] = 1;
                $total = $this->db->where($filter)->count_all_results('ml_post');
            } else { // 普通贴
                $filter['post_type <>'] = 1;
                $total = $this->db->where($filter)->where_in('post_type_extend', array(1,2,3))->count_all_results('ml_post');
            }

            return (string)$total;
        }

        public function is_first_post($user_id)
        {
            $post_count = (string)$this->postm->get_post_count(array("author_id"=>$user_id));
            return $post_count == 1 ? true : false;
        }

        public function first_post_info($user_id)
        {
            $result =  $this->db->select()->from("ml_post")->where('author_id', $user_id)->order_by('id','asc')->limit(1,0)->get()->result_array();
            return $result[0];
        }

        /**
         * 增加帖子收藏数
         * @param $post_id
         * @return object
         */
        public function inc_post_favorite_num($post_id, $post_type_extend = 0)
        {
            // 更新redis缓存
            $this->load->model('redism');
            if (in_array($post_type_extend, array(0,1,2,3))) {
                $this->redism->zset_incr_favorite_total($post_id, 1);
            }

            $key = POST_INFO_PREFIX.$post_id;
            $res = $this->redis->hIncrBy($key, 'favorite_total', 1);
            $result = '';
            if ($res) {
                $this->db->set('favorite_count', 'favorite_count+1', FALSE);
                $this->db->where(array("id"=>(int)$post_id));
                $result = $this->db->update("ml_post");
            }
            return $result;
        }


        /* 2.2版本代码 */

        /**
         * 减少帖子收藏数
         * @param $post_id
         * @return object
         */
        public function dec_post_favorite_num($post_id, $post_type_extend = 0)
        {
            // 更新rss redis缓存
            $this->load->model('redism');
            if (in_array($post_type_extend, array(0,1,2,3))) {
                $this->redism->zset_incr_favorite_total($post_id, -1);
            }

            $key = POST_INFO_PREFIX.$post_id;
            $res = $this->redis->hIncrBy($key, 'favorite_total', -1);

            $result = '';
            if ($res) {
                $this->db->set('favorite_count', 'favorite_count-1', FALSE);
                $this->db->where(array("id"=>(int)$post_id));
                $result = $this->db->update("ml_post");
            }

            return $result;
        }

        /* 获取检索标签 */

        public function get_post_aspect_ratio($post_imgs)
        {
            if(!is_array($post_imgs))
            {
                $post_imgs = explode(",", rtrim($post_imgs,","));
            }

            $this->load->model('imagem');
            $max = 0;
            foreach($post_imgs as $img_path) {
                $mc = $this->cache->memcached;
                $key = IMAGE_RATIO_KEY . $img_path;
                $this->cache->memcached->is_supported();

                $img_info = $this->imagem->getimagesize($img_path);
                if($img_info[0])
                {
                    $first_ratio = $img_info[1] / $img_info[0]; // 高/宽
                }
                if($img_info[1] == 0 || $img_info[0] == 0)
                {
                    $first_ratio = 1;
                }
                if ($first_ratio > $max) {
                    $max = $first_ratio;
                }
                $mc->save($key,$first_ratio,60*60*24*10);
            }

            $aspect_ratio = 1.6;
            if ($max) {
                $aspect_ratio = $max;
            }
            return $aspect_ratio;
        }

        /* 新增投票帖子 */

        /**
         * 获取帖子 所属科室ID  标签ID
         * @param $post_id
         * @param int $type
         * @return array
         */
        public function get_post_type_ids($post_id, $type = 0)
        {
            $filter = array('post_id' => $post_id, 'count >=' => 1);
            if ($type) $filter['type'] = $type;

            $list = $this->db->select('type_id, type')->from('ml_posttype')->where($filter)->get()->result_array();
            if (!$list) return array();

            $thread_ids = $tag_ids = array();
            foreach($list as $v) {
                if ($v['type'] == 1) {
                    $thread_ids[] = $v['type_id'];
                } else {
                    $tag_ids[] = $v['type_id'];
                }
            }

            return array('thread_ids' => $thread_ids, 'tag_ids' => $tag_ids);
        }


        /* 方法改写 */

        public function insert_release($data)
        {
            $result = $this->db->insert("ml_release",$data);
            if($result)
            {
                $post_id = $this->db->insert_id();
            }
            else
            {
                $return = false;
            }
            return $post_id;
        }

        /* 获取投票选项 */

        public function get_tag_list($search, $page, $page_size)
        {
            $start = ($page-1)*$page_size;
            $res = $this->db
                ->select('id,tag_name')
                ->from('ml_tags')
                ->like('tag_name',$search)
                ->order_by('addtime','desc')
                ->limit($page_size,$start)
                ->get()
                ->result_array();
            if(count($res) == 0)
            {
                return false;
            }
            return $res;
        }

        /* 查询投票信息 */

        public function insert_post_vote_option($data)
        {
            $result = $this->db->insert("ml_vote_option",$data);
            if(!$result)
            {
                return false;
            }
            return true;
        }


        /* 投票操作  */

        public function vote_ml_option($user_id,$option_id,$post_id)
        {
            $this->db->set('count', 'count+1', false);
            $this->db->where("id",$option_id);
            $this->db->where("post_id",$post_id);
            $res= $this->db->update('ml_vote_option');
            return $res;
        }

        /* 更新投票关联表 */
        public function update_vote_relation($user_id,$option_id,$post_id)
        {
            $data['clicker_id'] = $user_id;
            $data['post_id'] = $post_id;
            $data['option_id'] = $option_id;
            $data['addtime'] = time();
            $result = $this->db->insert("ml_vote_relation",$data);
            if(!$result)
            {
                return false;
            }
            return true;
        }

        /* 获取投票总信息 */
        public function vote_info_by_user($post_id)
        {
            $res = $this->db
                ->select('id,option,count,sort')
                ->from('ml_vote_option')
                ->where('post_id',$post_id)
                ->get()
                ->result_array();
            return $res;
        }

        /* 获取用户科室订阅状态 */
        public function get_user_thread_status($user_id,$type_id,$dis_cate_flag)
        {
            $result = $this->db
                ->select('id')
                ->from('ml_userrss')
                ->where(array('user_id'=>$user_id,'type_id'=>$type_id,'type'=>$dis_cate_flag))
                ->get()
                ->result_array();
            if(isset($result[0]['id']) && $result[0]['id'])
            {
                return '1';
            }
            return '0';
        }

        /* 即将成为品牌帖 */
        public function post_apply_for_brand($post_id)
        {
            $this->db->set('is_pinpai', 1);
            $this->db->where("id",$post_id);
            $res = $this->db->update('ml_post');
            if(!$res){
                return false;
            }
            return true;
        }

        /* 获取帖子标签+分类 */
        public function get_typepost_list($post_id)
        {
            $thread_list = $this->db
                ->select('a.type,b.id,b.thread_name as type_name,b.top_id,b.parent_id')
                ->from('ml_posttype as a')
                ->where(array('a.post_id' => $post_id, 'a.type' => 1))
                ->join('ml_thread as b','a.type_id=b.id','left')
                ->group_by('a.type_id')
                ->get()
                ->result_array();

            $tag_list = $this->db
                ->select('a.type,b.id,b.tag_name as type_name')
                ->from('ml_posttype as a')
                ->where(array('a.post_id' => $post_id, 'a.type' => 2))
                ->join('ml_tags as b', 'a.type_id=b.id', 'left')
                ->group_by('a.type_id')
                ->get()
                ->result_array();

            $type_list = array_merge($thread_list, $tag_list);

            // 话题兼容, 表示 话题分类type值为 3
            if (version_compare($this->softversion, '2.2.2') >= 0) {
                $this->config->load('thread');
                $topic_id = $this->config->item('topic_id');
                $topic_type = $this->config->item('topic_type');
                foreach($type_list as $k => $item) {
                    if (isset($item['top_id']) && $item['top_id'] == $topic_id) {
                        $type_list[$k]['type'] = $topic_type;
                    }
                }
            }

            return $type_list;
        }

        /* 获取帖子对应权限者 */
        public function get_security_ids($uid)
        {
            $res = $this->db
                ->select('thread_id')
                ->from('op_permission')
                ->where('user_id',$uid)
                ->get()
                ->result_array();
            if(!$res)
            {
                return false;
            }
            return $res[0]['thread_id'];
        }

        /* 根据类型获取所有帖子列表 */
        public function get_all_post_list($post_type_extend,$page,$page_size)
        {
            $mc = $this->cache->memcached;
            $this->cache->memcached->is_supported();
            $key = self::MC_KEY_ALLPOSTLIST.$post_type_extend;
            $res = $mc->get($key);
            if(!$res)
            {
                $start = ($page-1)*$page_size;
                if(isset($post_type_extend) && !$post_type_extend)
                {
                    # 获取所有列表
                    return false;
                }
                # 分条件获取
                if($post_type_extend == 100)
                {
                    $res = $this->db
                        ->select()
                        ->from('ml_post')
                        ->where('is_pinpai',2)
                        ->limit($page_size,$start)
                        ->get()
                        ->result_array();
                }
                $mc->save($key,$res,30*60);
            }
            if(!$res)
            {
                return false;
            }
            return $res;
        }

        // 验证投票是否重复
        public function check_repeat_vote($uid, $post_id, $option_id)
        {
            $res = $this->db
                ->from('ml_vote_relation')
                ->where(array('post_id' => $post_id, 'clicker_id' => $uid))
                ->get()
                ->num_rows();
            return $res;
        }

        public function update_special_qv($post_id, $flag = 0)
        {
            $this->db->set('special_qv', $flag);
            $this->db->where("id", $post_id);
            return $this->db->update('ml_post');
        }

        public function get_post_extend($post_id)
        {
            $res = $this->db->select('post_type_extend')->from('ml_post')->where('id', $post_id)->get()->result_array();
            return $res[0]['post_type_extend'];
        }
        //获取最新一条推荐帖子id
        public function  get_one_recommend($type,$type_id,$post_type_extend=100)
        {
            $this->db->select('post_id')->from('ml_digest_log');
            if($type == 1)
            {
                $this->db->where('thread',$type_id);
            }else{
                $this->db->where('tags',$type_id);
            }
            $this->db->where('end_time>',time());
            $this->db->where('post_type_extend',$post_type_extend);
            return $this->db->order_by('id','desc')->get()->row_array();

        }

        // 2.2.2版本优化个人中心（查询本人的发帖总数）
        public function get_my_total_post_count($author_id)
        {
            $filters = array('author_id' => $author_id, 'is_show' => 1,'post_type<>'=>1);
            $post_count = $this->db
                ->where($filters)
                ->where_not_in('post_type_extend', array(4,5,6))
                ->count_all_results("ml_post");
            return $post_count;
        }

        // 2.2.2版本优化个人中心（查询别人的发帖总数）
        public function get_other_total_post_count($author_id)
        {
            $filters = array('author_id' => $author_id, 'is_show' => 1, 'post_type <>' => 1);
            $post_count = $this->db
                ->where($filters)
                ->where_not_in('post_type_extend', array(4, 5, 6))
                ->count_all_results("ml_post");
            return $post_count;
        }

        // 2.2.2版本优化个人中心（查询发帖总数）
        public function get_total_brand_count($user_id)
        {
            $filters = array('is_show' => 1, 'is_pinpai' => 2, 'author_id' => $user_id);
            $total_count = $this->db
                ->where($filters)
                ->count_all_results('ml_post');
            return $total_count;
        }

        /* 版主帖子extend转换 */
        public function transfer_post_type($post_id, $post_type_extend)
        {
            $this->db->set('post_type_extend', $post_type_extend);
            $this->db->where("id", $post_id);
            return $this->db->update('ml_post');
        }


        /**
         * 获取帖子实体内容
         * @param $post_id
         * @param null $post_info
         * @return string
         */
        public function getPostContent($post_id, $post_info = null)
        {
            if (!$post_info) {
                $post_info = Postm::get_post_content($post_id);
            }

            // 1专家帖, 11求助帖
            if($post_info['post_type'] == 1 || $post_info['post_type'] == 11 ) {
                if ($post_info['post_type_extend'] == 1 || $post_info['post_type_extend'] == 2) {
                    $content = $this->get_specialist_post_info_extend($post_id);
                } else {
                    $content = $this->get_specialist_post_info($post_id);
                }
            }
            else {
                $content = $post_info["message"];
            }
            
            return $content;
        }

        /**
         * 不同版主自动推荐三次,自动成为品牌帖
         * @param $post_id
         * @param $leader_id
         */
        public function InsertPinpaiLog($post_id,$leader_id,$platform)
        {
            $sql = $this->db->from('ml_pinpai_log')->where(array('post_id'=>$post_id,'leader_id'=>$leader_id))->get()->row_array();
            if(!$sql)
            {
                $data =  array('post_id'=>$post_id,'leader_id'=>$leader_id,'addtime'=>time());
                $this->db->insert('ml_pinpai_log',$data);
            }
            $count = $this->db->select( 'count(distinct(leader_id)) as sum')->from('ml_pinpai_log')->where('post_id',$post_id)->get()->row_array();
            if($count['sum']>=3)
            {
                $this->adminlogm->insert_admin_log($post_id, $type = 16, $leader_id, $platform);
                $this->db->set('is_pinpai',2)->where('id',$post_id)->update('ml_post');
            }
            return true;

        }

        // 获取用户是否对标的物进行打赏
        public function get_acc_point_flag($uid, $type, $related_id)
        {
            $filters = array('user_id' => $uid, 'type' => $type, 'related_id' => $related_id);
            $count = $this->db
                ->where($filters)
                ->count_all_results("ml_admin_reward_jfpoint_log");
            return $count;
        }

        // 版主积分打赏日志记录
        public function moderator_award_point_log($moderator_id, $uid = 0, $related_id = 0, $type = 1, $point = 0)
        {
            $filters = array(
                'moderator_id' => $moderator_id,
                'type' => $type,
                'user_id' => $uid,
                'point_count' => $point,
                'related_id' => $related_id,
                'addtime' => time()
            );
            return $this->db->insert("ml_admin_reward_jfpoint_log", $filters);
        }

        // 查看帖子发布人ID
        public function post_author_id($post_id = 0, $table = '')
        {
            $filters = array(
                'id' => $post_id,
                'is_show' => 1
            );
            $res = $this->db->select('author_id')->from($table)->where($filters)->get()->row_array();
            if (empty($res)) {
                return false;
            }
            return $res['author_id'];
        }

        public function getBonusMoney($post_id)
        {
            $filters = array('id' => $post_id, 'is_show' => 1);
            $query = $this->db->select('post_money')->from('ml_post')->where($filters)->get();

            $money = 0;
            if ($query) {
                $data = $query->row_array();
                $money = isset($data['post_money']) ? $data['post_money'] : 0;
            }

            return $money;
        }
        /**
         * 通过帖子id或者评论id查询username
         * type:1帖子,2:评论
         */
        public function get_username_receipt($uid,$op_user,$affect_user)
        {
             if($uid == $op_user)
             {
                 $id = $affect_user;
             }else{
                 $id = $op_user;
             }
             $res = $this->db->select('id as author_id,username as author_name')->from('ml_fellow')->where('id',$id)->get()->row_array();
             return $res;
        }
    }

